diff --git a/CHANGELOG.md b/CHANGELOG.md index 6212724..586cad6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ - you can find the wasm version of ammo.js in `babylon-mmd/esm/Runtime/Physics/External/ammo.wasm` - this distribution of ammo.js has been modified to work with bundlers like Webpack +- fix bpmx converter does not serialize bone flags correctly + ## 0.46.0 (2024-06-08) - improve CreateMmdModelOptions parameter type diff --git a/docs/static/pmx_converter/main.bundle.js b/docs/static/pmx_converter/main.bundle.js index fbb5b9a..a6158f7 100644 --- a/docs/static/pmx_converter/main.bundle.js +++ b/docs/static/pmx_converter/main.bundle.js @@ -1 +1 @@ -(()=>{"use strict";var e,t,i,s,r={535:(e,t,i)=>{i.d(t,{u:()=>ta});var s=i(326);class r{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;r.DefaultLogoUrl?t.src=r.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(r.DefaultSpinnerUrl?s.src=r.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}r.DefaultLogoUrl="",r.DefaultSpinnerUrl="",s.$.DefaultLoadingScreenFactory=e=>new r(e);const n=1/2.2,a=(Math.sqrt(5),.001);class o{static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}const c={};function d(e,t){c[e]=t}function u(e){return c[e]}var f=i(215),_=i(315);function p(e,t,i=1401298e-51){return Math.abs(e-t)<=i}function g(e,t){return e===t?e:Math.random()*(t-e)+e}function m(e,t,i){return e+(t-e)*i}function T(e,t=0,i=1){return Math.min(i,Math.max(t,e))}function x(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function E(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}const v=e=>parseInt(e.toString().replace(/\W/g,""));class A{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=v(this.x);return e=397*e^v(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return A.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 A(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 A(this.x+e.x,this.y+e.y)}subtract(e){return new A(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 A(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 A(this.x*e,this.y*t)}divide(e){return new A(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 A(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 A(-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 A(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=a){return e&&p(this.x,e.x,t)&&p(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new A(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 A(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),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new A;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new A(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new A(0,0)}static One(){return new A(1,1)}static Random(e=0,t=1){return new A(g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(g(e,t),g(e,t))}static get ZeroReadOnly(){return A._ZeroReadOnly}static FromArray(e,t=0){return new A(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,r){const n=r*r,a=r*n,o=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*a),h=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*a);return new A(o,h)}static ClampToRef(e,t,i,s){return s.x=T(e.x,t.x,i.x),s.y=T(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=T(e.x,t.x,i.x),r=T(e.y,t.y,i.y);return new A(s,r)}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e.x*o+i.x*h+t.x*l+s.x*c,u=e.y*o+i.y*h+t.y*l+s.y*c;return new A(d,u)}static Hermite1stDerivative(e,t,i,s,r){return this.Hermite1stDerivativeToRef(e,t,i,s,r,new A)}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;return n.x=6*(a-r)*e.x+(3*a-4*r+1)*t.x+6*(-a+r)*i.x+(3*a-2*r)*s.x,n.y=6*(a-r)*e.y+(3*a-4*r+1)*t.y+6*(-a+r)*i.y+(3*a-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new A(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return A.NormalizeToRef(e,new A)}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 A(i,s)}static Transform(e,t){return A.TransformToRef(e,t,new A)}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,a=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return a>0&&o>0&&a+o<2*r*n}static Distance(e,t){return Math.sqrt(A.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 A.CenterToRef(e,t,new A)}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=A.DistanceSquared(t,i);if(0===s)return A.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,A.Dot(e.subtract(t),r)/s)),a=t.add(r.multiplyByFloats(n,n));return A.Distance(e,a)}}A._ZeroReadOnly=A.Zero(),Object.defineProperties(A.prototype,{dimension:{value:[2]},rank:{value:1}});class M{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=v(this._x);return e=397*e^v(this._y),e=397*e^v(this._z),e}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 M.FromArrayToRef(e,t,this),this}toQuaternion(){return S.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 M(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new M(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 M(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new M(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new M(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(s);return e.set(r,n,a),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,a=e._y,o=e._z,h=e._w,l=2*(a*r-o*s),c=2*(o*i-n*r),d=2*(n*s-a*i);return t._x=i+h*l+a*d-o*c,t._y=s+h*c+o*l-n*d,t._z=r+h*d+n*c-a*l,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new M)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new M)}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=I.Vector3[0];this.subtractToRef(t,n),n.normalize();const a=M.Dot(n,s);if(Math.abs(a)<1e-10)i.setAll(1/0);else{const e=-(M.Dot(t,s)+r)/a,o=n.scaleInPlace(e);t.addToRef(o,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=a){return e&&p(this._x,e._x,t)&&p(this._y,e._y,t)&&p(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new M(this._x*e,this._y*t,this._z*i)}divide(e){return new M(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!p(t,i,e))return!0;const s=Math.abs(this._z);return!p(t,s,e)||!p(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}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 M(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 M(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("xyz"===(e=e.toLowerCase()))return this;const t=I.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(I.Matrix[0]),M.TransformCoordinatesToRef(this,I.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,I.Vector3[0]),I.Vector3[0].rotateByQuaternionToRef(e,I.Vector3[0]),t.addToRef(I.Vector3[0],i),i}cross(e){return M.CrossToRef(this,e,new M)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new M)}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new M(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=M.Dot(e,i);return(r-s)/(r-M.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(I.Vector3[1]),r=t.normalizeToRef(I.Vector3[2]);let n=M.Dot(s,r);n=T(n,-1,1);const a=Math.acos(n),o=I.Vector3[3];return M.CrossToRef(s,r,o),M.Dot(o,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){I.Vector3[0].copyFrom(e);const s=I.Vector3[0];I.Vector3[1].copyFrom(t);const r=I.Vector3[1];I.Vector3[2].copyFrom(i);const n=I.Vector3[2],a=I.Vector3[3],o=I.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),M.CrossToRef(n,s,a),M.CrossToRef(a,n,o),x(Math.atan2(M.Dot(r,a),M.Dot(r,o)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=R.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=M.Zero();return M.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=T(i,0,1);const r=I.Vector3[0],n=I.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const h=n.length();n.normalizeFromLength(h);const l=M.Dot(r,n);let c,d;if(l<1-a){const e=Math.acos(l),t=1/Math.sin(e);c=Math.sin((1-i)*e)*t,d=Math.sin(i*e)*t}else c=1-i,d=i;return r.scaleInPlace(c),n.scaleInPlace(d),s.copyFrom(r).addInPlace(n),s.scaleInPlace(m(o,h,i)),s}static SmoothToRef(e,t,i,s,r){return M.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new M(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return M.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 M.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new M(0,0,0)}static One(){return new M(1,1,1)}static Up(){return new M(0,1,0)}static get UpReadOnly(){return M._UpReadOnly}static get DownReadOnly(){return M._DownReadOnly}static get RightReadOnly(){return M._RightReadOnly}static get LeftReadOnly(){return M._LeftReadOnly}static get LeftHandedForwardReadOnly(){return M._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return M._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return M._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return M._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return M._ZeroReadOnly}static get OneReadOnly(){return M._OneReadOnly}static Down(){return new M(0,-1,0)}static Forward(e=!1){return new M(0,0,e?-1:1)}static Backward(e=!1){return new M(0,0,e?1:-1)}static Right(){return new M(1,0,0)}static Left(){return new M(-1,0,0)}static Random(e=0,t=1){return new M(g(e,t),g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(g(e,t),g(e,t),g(e,t))}static TransformCoordinates(e,t){const i=M.Zero();return M.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return M.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],o=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],l=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=a*l,r._y=o*l,r._z=h*l,r._isDirty=!0,r}static TransformNormal(e,t){const i=M.Zero();return M.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,a=r*n,o=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*a),h=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*a),l=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*a);return new M(o,h,l)}static Clamp(e,t,i){const s=new M;return M.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:a,a=a0&&C<0?(D.copyFrom(n),O=t,F=i):C>0&&P<0?(D.copyFrom(h),O=i,F=s):(D.copyFrom(o).scaleInPlace(-1),O=s,F=t);const w=I.Vector3[9],L=I.Vector3[4];if(O.subtractToRef(x,b),F.subtractToRef(x,w),M.CrossToRef(b,w,L),!(M.Dot(L,l)<0))return r.copyFrom(x),Math.abs(p*g);const N=I.Vector3[5];M.CrossToRef(D,L,N),N.normalize();const B=I.Vector3[9];B.copyFrom(O).subtractInPlace(x);const U=B.length();if(Uthis.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 b(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 b(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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new b)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(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 M(this.x,this.y,this.z)}clone(){return new b(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 b(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 b.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new b(0,0,0,0)}static One(){return new b(1,1,1,1)}static Random(e=0,t=1){return new b(g(e,t),g(e,t),g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.x=g(e,t),i.y=g(e,t),i.z=g(e,t),i.w=g(e,t),i}static Clamp(e,t,i){return b.ClampToRef(e,t,i,new b)}static ClampToRef(e,t,i,s){return s.x=T(e.x,t.x,i.x),s.y=T(e.y,t.y,i.y),s.z=T(e.z,t.z,i.z),s.w=T(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return b._ZeroReadOnly}static Normalize(e){return b.NormalizeToRef(e,new b)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new b;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new b;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(b.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return b.CenterToRef(e,t,new b)}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 b.TransformCoordinatesToRef(e,t,new b)}static TransformCoordinatesToRef(e,t,i){return b.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],o=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],l=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=a,r.y=o,r.z=h,r.w=l,r}static TransformNormal(e,t){return b.TransformNormalToRef(e,t,new b)}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],a=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const a=r.m;return n.x=e*a[0]+t*a[4]+i*a[8],n.y=e*a[1]+t*a[5]+i*a[9],n.z=e*a[2]+t*a[6]+i*a[10],n.w=s,n}static FromVector3(e,t=0){return new b(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}}b._ZeroReadOnly=b.Zero(),Object.defineProperties(b.prototype,{dimension:{value:[4]},rank:{value:1}});class S{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=v(this._x);return e=397*e^v(this._y),e=397*e^v(this._z),e=397*e^v(this._w),e}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 S.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=a){return e&&p(this._x,e._x,t)&&p(this._y,e._y,t)&&p(this._z,e._z,t)&&p(this._w,e._w,t)}clone(){return new S(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 S(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 S)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new S(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 S(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 S(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}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 S)}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 S(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new S(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=M.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,a=.4999999;if(n<-a)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>a)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const a=r*r,o=t*t,h=i*i,l=s*s;e._z=Math.atan2(2*(i*s+t*r),-o-h+l+a),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),o-h-l+a),e._isDirty=!0}return e}toRotationMatrix(e){return y.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return S.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 S;return S.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[1],o=i[5],h=i[9],l=i[2],c=i[6],d=i[10],u=s+o+d;let f;return u>0?(f=.5/Math.sqrt(u+1),t._w=.25/f,t._x=(c-h)*f,t._y=(n-l)*f,t._z=(a-r)*f,t._isDirty=!0):s>o&&s>d?(f=2*Math.sqrt(1+s-o-d),t._w=(c-h)/f,t._x=.25*f,t._y=(r+a)/f,t._z=(n+l)/f,t._isDirty=!0):o>d?(f=2*Math.sqrt(1+o-s-d),t._w=(n-l)/f,t._x=(r+a)/f,t._y=.25*f,t._z=(h+c)/f,t._isDirty=!0):(f=2*Math.sqrt(1+d-s-o),t._w=(a-r)/f,t._x=(n+l)/f,t._y=(h+c)/f,t._z=.25*f,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=S.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=T(n,0,1),S.SlerpToRef(e,t,n,r),r}static Zero(){return new S(0,0,0,0)}static Inverse(e){return new S(-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 S(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return S.RotationAxisToRef(e,t,new S)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new S(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,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new S;return S.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return S.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new S;return S.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return S.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=a){const r=M.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(M.CrossToRef(e,t,R.Vector3[0]),i.set(R.Vector3[0].x,R.Vector3[0].y,R.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new S;return S.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,a=.5*e,o=Math.sin(r),h=Math.cos(r),l=Math.sin(n),c=Math.cos(n),d=Math.sin(a),u=Math.cos(a);return s._x=u*l*h+d*c*o,s._y=d*c*h-u*l*o,s._z=u*c*o-d*l*h,s._w=u*c*h+d*l*o,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new S;return S.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),a=.5*t;return s._x=Math.cos(n)*Math.sin(a),s._y=Math.sin(n)*Math.sin(a),s._z=Math.sin(r)*Math.cos(a),s._w=Math.cos(r)*Math.cos(a),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new S(0,0,0,0);return S.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=I.Matrix[0];return y.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),S.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new S;return S.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=I.Matrix[0];return y.LookDirectionLHToRef(e,t,s),S.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new S;return S.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=I.Matrix[0];return y.LookDirectionRHToRef(e,t,s),S.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=S.Identity();return S.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,o=!1;if(a<0&&(o=!0,a=-a),a>.999999)n=1-i,r=o?-i:i;else{const e=Math.acos(a),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e._x*o+i._x*h+t._x*l+s._x*c,u=e._y*o+i._y*h+t._y*l+s._y*c,f=e._z*o+i._z*h+t._z*l+s._z*c,_=e._w*o+i._w*h+t._w*l+s._w*c;return new S(d,u,f,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new S;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;return n._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*i._x+(3*a-2*r)*s._x,n._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*i._y+(3*a-2*r)*s._y,n._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*i._z+(3*a-2*r)*s._z,n._w=6*(a-r)*e._w+(3*a-4*r+1)*t._w+6*(-a+r)*i._w+(3*a-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=S.Zero();return S.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new S;return S.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(T(e.x,t.x,i.x),T(e.y,t.y,i.y),T(e.z,t.z,i.z),T(e.w,t.w,i.w))}static Random(e=0,t=1){return new S(g(e,t),g(e,t),g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(g(e,t),g(e,t),g(e,t),g(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(S.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return S.CenterToRef(e,t,S.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(S.prototype,{dimension:{value:[4]},rank:{value:1}});class y{static get Use64Bits(){return f.I.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=y._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&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,f.I.MatrixTrackPrecisionChange&&f.I.MatrixTrackedMatrices.push(this),this._m=new f.I.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==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]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8],c=e[9],d=e[10],u=e[11],f=e[12],_=e[13],p=e[14],g=e[15],m=d*g-p*u,T=c*g-_*u,x=c*p-_*d,E=l*g-f*u,v=l*p-d*f,A=l*_-f*c;return t*+(a*m-o*T+h*x)+i*-(n*m-o*E+h*v)+s*+(n*T-a*E+h*A)+r*-(n*x-a*v+o*A)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return y.FromArrayToRef(e,t,this)}copyFromFloats(...e){return y.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 y.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 y;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];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 e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new y)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return y.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],a=t[4],o=t[5],h=t[6],l=t[7],c=t[8],d=t[9],u=t[10],f=t[11],_=t[12],p=t[13],g=t[14],m=t[15],T=u*m-g*f,x=d*m-p*f,E=d*g-p*u,v=c*m-_*f,A=c*g-u*_,M=c*p-_*d,b=+(o*T-h*x+l*E),S=-(a*T-h*v+l*A),I=+(a*x-o*v+l*M),R=-(a*E-o*A+h*M),C=i*b+s*S+r*I+n*R;if(0===C)return e.copyFrom(this),e;const P=1/C,D=h*m-g*l,O=o*m-p*l,F=o*g-p*h,w=a*m-_*l,L=a*g-_*h,N=a*p-_*o,B=h*f-u*l,U=o*f-d*l,k=o*u-d*h,V=a*f-c*l,G=a*u-c*h,z=a*d-c*o,W=-(s*T-r*x+n*E),X=+(i*T-r*v+n*A),H=-(i*x-s*v+n*M),K=+(i*E-s*A+r*M),Y=+(s*D-r*O+n*F),q=-(i*D-r*w+n*L),j=+(i*O-s*w+n*N),Z=-(i*F-s*L+r*N),Q=-(s*B-r*U+n*k),$=+(i*B-r*V+n*G),J=-(i*U-s*V+n*z),ee=+(i*k-s*G+r*z);return y.FromValuesToRef(b*P,W*P,Y*P,Q*P,S*P,X*P,q*P,$*P,I*P,H*P,j*P,J*P,R*P,K*P,Z*P,ee*P,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 M(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 y.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),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 y;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];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,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];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,r=e.m,n=s[0],a=s[1],o=s[2],h=s[3],l=s[4],c=s[5],d=s[6],u=s[7],f=s[8],_=s[9],p=s[10],g=s[11],m=s[12],T=s[13],x=s[14],E=s[15],v=r[0],A=r[1],M=r[2],b=r[3],S=r[4],y=r[5],I=r[6],R=r[7],C=r[8],P=r[9],D=r[10],O=r[11],F=r[12],w=r[13],L=r[14],N=r[15];return t[i]=n*v+a*S+o*C+h*F,t[i+1]=n*A+a*y+o*P+h*w,t[i+2]=n*M+a*I+o*D+h*L,t[i+3]=n*b+a*R+o*O+h*N,t[i+4]=l*v+c*S+d*C+u*F,t[i+5]=l*A+c*y+d*P+u*w,t[i+6]=l*M+c*I+d*D+u*L,t[i+7]=l*b+c*R+d*O+u*N,t[i+8]=f*v+_*S+p*C+g*F,t[i+9]=f*A+_*y+p*P+g*w,t[i+10]=f*M+_*I+p*D+g*L,t[i+11]=f*b+_*R+p*O+g*N,t[i+12]=m*v+T*S+x*C+E*F,t[i+13]=m*A+T*y+x*P+E*w,t[i+14]=m*M+T*I+x*D+E*L,t[i+15]=m*b+T*R+x*O+E*N,this}divide(e){return this.divideToRef(e,new y)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 y)}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 e=0;e<16;e++)i[e]=-t[e];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 e=0;e<16;e++)if(!p(i[e],s[e],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 y)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new y)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new y;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=v(this._m[0]);for(let t=1;t<16;t++)e=397*e^v(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new S,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||I.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;y.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,I.Matrix[0]),S.FromRotationMatrixToRef(I.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new b(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=4*e;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 y;return y.TransposeToRef(this,e),e}transposeToRef(e){return y.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new y;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=I.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return y.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 y;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=I.Vector3[0];if(!this.decompose(t))return y.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return y.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new y;return y.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return y._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,a,o,h,l,c,d,u,f,_,p,g){const m=g._m;m[0]=e,m[1]=t,m[2]=i,m[3]=s,m[4]=r,m[5]=n,m[6]=a,m[7]=o,m[8]=h,m[9]=l,m[10]=c,m[11]=d,m[12]=u,m[13]=f,m[14]=_,m[15]=p,g.markAsUpdated()}static FromValues(e,t,i,s,r,n,a,o,h,l,c,d,u,f,_,p){const g=new y,m=g._m;return m[0]=e,m[1]=t,m[2]=i,m[3]=s,m[4]=r,m[5]=n,m[6]=a,m[7]=o,m[8]=h,m[9]=l,m[10]=c,m[11]=d,m[12]=u,m[13]=f,m[14]=_,m[15]=p,g.markAsUpdated(),g}static Compose(e,t,i){const s=new y;return y.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,a=t._y,o=t._z,h=t._w,l=n+n,c=a+a,d=o+o,u=n*l,f=n*c,_=n*d,p=a*c,g=a*d,m=o*d,T=h*l,x=h*c,E=h*d,v=e._x,A=e._y,M=e._z;return r[0]=(1-(p+m))*v,r[1]=(f+E)*v,r[2]=(_-x)*v,r[3]=0,r[4]=(f-E)*A,r[5]=(1-(u+m))*A,r[6]=(g+T)*A,r[7]=0,r[8]=(_+x)*M,r[9]=(g-T)*M,r[10]=(1-(u+p))*M,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=y.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 y.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=y.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 y;return y.RotationXToRef(e,t),t}static Invert(e){const t=new y;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return y.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new y;return y.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return y.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new y;return y.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return y.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new y;return y.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const a=i._m;return a[0]=e._x*e._x*n+r,a[1]=e._x*e._y*n-e._z*s,a[2]=e._x*e._z*n+e._y*s,a[3]=0,a[4]=e._y*e._x*n+e._z*s,a[5]=e._y*e._y*n+r,a[6]=e._y*e._z*n-e._x*s,a[7]=0,a[8]=e._z*e._x*n-e._y*s,a[9]=e._z*e._y*n+e._x*s,a[10]=e._z*e._z*n+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=M.Dot(t,e),n=i._m;if(r<-1+a)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=M.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new y;return y.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return S.RotationYawPitchRollToRef(e,t,i,I.Quaternion[0]),I.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new y;return y.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return y.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new y;return y.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return y.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new y;return y.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,a=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+a[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new y;return y.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=I.Vector3[0],n=I.Quaternion[0],a=I.Vector3[1];e.decompose(r,n,a);const o=I.Vector3[2],h=I.Quaternion[1],l=I.Vector3[3];t.decompose(o,h,l);const c=I.Vector3[4];M.LerpToRef(r,o,i,c);const d=I.Quaternion[2];S.SlerpToRef(n,h,i,d);const u=I.Vector3[5];return M.LerpToRef(a,l,i,u),y.ComposeToRef(c,d,u,s),s}static LookAtLH(e,t,i){const s=new y;return y.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=I.Vector3[0],n=I.Vector3[1],a=I.Vector3[2];t.subtractToRef(e,a),a.normalize(),M.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),M.CrossToRef(a,r,n),n.normalize();const h=-M.Dot(r,e),l=-M.Dot(n,e),c=-M.Dot(a,e);return y.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,s),s}static LookAtRH(e,t,i){const s=new y;return y.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=I.Vector3[0],n=I.Vector3[1],a=I.Vector3[2];e.subtractToRef(t,a),a.normalize(),M.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),M.CrossToRef(a,r,n),n.normalize();const h=-M.Dot(r,e),l=-M.Dot(n,e),c=-M.Dot(a,e);return y.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,s),s}static LookDirectionLH(e,t){const i=new y;return y.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=I.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=I.Vector3[1];return M.CrossToRef(t,s,r),y.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new y;return y.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=I.Vector3[2];return M.CrossToRef(t,e,s),y.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new y;return y.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const a=2/e,o=2/t,h=2/(s-i),l=-(s+i)/(s-i);return y.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,h,0,0,0,l,1,r),n&&r.multiplyToRef(C,r),r._updateIdentityStatus(1===a&&1===o&&1===h&&0===l),r}static OrthoOffCenterLH(e,t,i,s,r,n,a){const o=new y;return y.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o}static OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o){const h=2/(t-e),l=2/(s-i),c=2/(n-r),d=-(n+r)/(n-r),u=(e+t)/(e-t),f=(s+i)/(i-s);return y.FromValuesToRef(h,0,0,0,0,l,0,0,0,0,c,0,u,f,d,1,a),o&&a.multiplyToRef(C,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,a,o,h,l,c){const d=-a*Math.cos(o),u=-a*Math.sin(o);return y.TranslationToRef(0,0,-h,I.Matrix[1]),y.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,I.Matrix[0]),I.Matrix[1].multiplyToRef(I.Matrix[0],I.Matrix[0]),y.TranslationToRef(0,0,h,I.Matrix[1]),I.Matrix[0].multiplyToRef(I.Matrix[1],I.Matrix[0]),y.OrthoOffCenterLHToRef(e,t,i,s,r,n,l,c),I.Matrix[0].multiplyToRef(l,l),l}static OrthoOffCenterRH(e,t,i,s,r,n,a){const o=new y;return y.OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a),o}static OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o){return y.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,a,o,h,l,c){const d=a*Math.cos(o),u=a*Math.sin(o);return y.TranslationToRef(0,0,h,I.Matrix[1]),y.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,I.Matrix[0]),I.Matrix[1].multiplyToRef(I.Matrix[0],I.Matrix[0]),y.TranslationToRef(0,0,-h,I.Matrix[1]),I.Matrix[0].multiplyToRef(I.Matrix[1],I.Matrix[0]),y.OrthoOffCenterRHToRef(e,t,i,s,r,n,l,c),I.Matrix[0].multiplyToRef(l,l),l}static PerspectiveLH(e,t,i,s,r,n=0){const a=new y,o=2*i/e,h=2*i/t,l=(s+i)/(s-i),c=-2*s*i/(s-i),d=Math.tan(n);return y.FromValuesToRef(o,0,0,0,0,h,0,d,0,0,l,1,0,0,c,0,a),r&&a.multiplyToRef(C,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,s,r,n=0,a=!1){const o=new y;return y.PerspectiveFovLHToRef(e,t,i,s,o,!0,r,n,a),o}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,a,o=0,h=!1){const l=i,c=s,d=1/Math.tan(.5*e),u=n?d/t:d,f=n?d:d*t,_=h&&0===l?-1:0!==c?(c+l)/(c-l):1,p=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,g=Math.tan(o);return y.FromValuesToRef(u,0,0,0,0,f,0,g,0,0,_,1,0,0,p,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,d=Math.tan(o);return y.FromValuesToRef(l,0,0,0,0,c,0,d,0,0,-i,1,0,0,1,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,a=!1){const o=new y;return y.PerspectiveFovRHToRef(e,t,i,s,o,!0,r,n,a),o}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,a,o=0,h=!1){const l=i,c=s,d=1/Math.tan(.5*e),u=n?d/t:d,f=n?d:d*t,_=h&&0===l?1:0!==c?-(c+l)/(c-l):-1,p=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,g=Math.tan(o);return y.FromValuesToRef(u,0,0,0,0,f,0,g,0,0,_,-1,0,0,p,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,d=Math.tan(o);return y.FromValuesToRef(l,0,0,0,0,c,0,d,0,0,-i,-1,0,0,-1,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const a=e.width,o=e.height,h=e.x,l=e.y,c=y.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,n-r,0,h+a/2,o/2+l,r,1),d=new y;return t.multiplyToRef(i,d),d.multiplyToRef(s,d),d.multiplyToRef(c,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return f.I.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 f.I.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new y;return y.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[12],o=i[1],h=i[5],l=i[9],c=i[13],d=i[2],u=i[6],f=i[10],_=i[14],p=i[3],g=i[7],m=i[11],T=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=a,x[4]=o,x[5]=h,x[6]=l,x[7]=c,x[8]=d,x[9]=u,x[10]=f,x[11]=_,x[12]=p,x[13]=g,x[14]=m,x[15]=T,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new y;return y.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,a=-2*s,o=-2*r;return y.FromValuesToRef(n*i+1,a*i,o*i,0,n*s,a*s+1,o*s,0,n*r,a*r,o*r+1,0,n*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return y.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,a=e._z*e._w,o=e._z*e._x,h=e._y*e._w,l=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+a),t._m[2]=2*(o-h),t._m[3]=0,t._m[4]=2*(n-a),t._m[5]=1-2*(r+i),t._m[6]=2*(l+c),t._m[7]=0,t._m[8]=2*(o+h),t._m[9]=2*(l-c),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}}y._UpdateFlagSeed=0,y._IdentityReadOnly=y.Identity(),Object.defineProperties(y.prototype,{dimension:{value:[4,4]},rank:{value:2}});class I{}I.Vector3=o.BuildTuple(11,M.Zero),I.Matrix=o.BuildTuple(2,y.Identity),I.Quaternion=o.BuildTuple(3,S.Zero);class R{}R.Vector2=o.BuildTuple(3,A.Zero),R.Vector3=o.BuildTuple(13,M.Zero),R.Vector4=o.BuildTuple(3,b.Zero),R.Quaternion=o.BuildTuple(2,S.Zero),R.Matrix=o.BuildTuple(8,y.Identity),d("BABYLON.Vector2",A),d("BABYLON.Vector3",M),d("BABYLON.Vector4",b),d("BABYLON.Matrix",y);const C=y.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class P{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=P.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=P.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=P.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+P.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=P.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*T(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?T((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n;return e*(2*a-3*n+1)+i*(-2*a+3*n)+t*(a-2*n+r)+s*(a-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:P.HCF(t,i)}}function D(e){return Math.pow(e,2.2)}function O(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function F(e){return Math.pow(e,n)}function w(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}P.TwoPi=2*Math.PI,P.WithinEpsilon=p,P.ToHex=E,P.Clamp=T,P.Lerp=m,P.RandomRange=g,P.NormalizeRadians=x;class L{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=255*this.r|0;return e=397*e^(255*this.g|0),e=397*e^(255*this.b|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 L.FromArrayToRef(e,t,this),this}toColor4(e=1){return new N(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new L(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 L(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=a){return P.WithinEpsilon(this.r,e.r,t)&&P.WithinEpsilon(this.g,e.g,t)&&P.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new L(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=T(this.r,e,t),i.g=T(this.g,e,t),i.b=T(this.b,e,t),i}add(e){return new L(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 L(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 L(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 L(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(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+E(e)+E(t)+E(i)}toHSV(){return this.toHSVToRef(new L)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let a=0,o=0;const h=r,l=r-n;return 0!==r&&(o=l/r),r!=n&&(r==t?(a=(i-s)/l,i=0&&n<=1?(o=r,h=a):n>=1&&n<=2?(o=a,h=r):n>=2&&n<=3?(h=r,l=a):n>=3&&n<=4?(h=a,l=r):n>=4&&n<=5?(o=a,l=r):n>=5&&n<=6&&(o=r,l=a);const c=i-r;return s.r=o+c,s.g=h+c,s.b=l+c,s}static FromHSV(e,t,i){const s=new L(0,0,0);return L.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new L(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return L.FromInts(t,i,s)}static FromArray(e,t=0){return new L(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 L(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new L(0,0,0);return L.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e.r*o+i.r*h+t.r*l+s.r*c,u=e.g*o+i.g*h+t.g*l+s.g*c,f=e.b*o+i.b*h+t.b*l+s.b*c;return new L(d,u,f)}static Hermite1stDerivative(e,t,i,s,r){const n=L.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*s.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*s.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*s.b}static Red(){return new L(1,0,0)}static Green(){return new L(0,1,0)}static Blue(){return new L(0,0,1)}static Black(){return new L(0,0,0)}static get BlackReadOnly(){return L._BlackReadOnly}static White(){return new L(1,1,1)}static Purple(){return new L(.5,0,.5)}static Magenta(){return new L(1,0,1)}static Yellow(){return new L(1,1,0)}static Gray(){return new L(.5,.5,.5)}static Teal(){return new L(0,1,1)}static Random(){return new L(Math.random(),Math.random(),Math.random())}}L._BlackReadOnly=L.Black(),Object.defineProperties(L.prototype,{dimension:{value:[3]},rank:{value:1}});class N{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 N(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 N(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 N(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new N(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=T(this.r,e,t),i.g=T(this.g,e,t),i.b=T(this.b,e,t),i.a=T(this.a,e,t),i}multiply(e){return new N(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 N(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=a){return P.WithinEpsilon(this.r,e.r,t)&&P.WithinEpsilon(this.g,e.g,t)&&P.WithinEpsilon(this.b,e.b,t)&&P.WithinEpsilon(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=255*this.r|0;return e=397*e^(255*this.g|0),e=397*e^(255*this.b|0),e=397*e^(255*this.a|0),e}clone(){return(new N).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(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+E(t)+E(i)+E(s);const r=Math.round(255*this.a);return"#"+E(t)+E(i)+E(s)+E(r)}toLinearSpace(e=!1){const t=new N;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=O(this.r),e.g=O(this.g),e.b=O(this.b)):(e.r=D(this.r),e.g=D(this.g),e.b=D(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new N;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=w(this.r),e.g=w(this.g),e.b=w(this.b)):(e.r=F(this.r),e.g=F(this.g),e.b=F(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new N(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return N.FromInts(t,i,s,r)}static Lerp(e,t,i){return N.LerpToRef(e,t,i,new N)}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,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e.r*o+i.r*h+t.r*l+s.r*c,u=e.g*o+i.g*h+t.g*l+s.g*c,f=e.b*o+i.b*h+t.b*l+s.b*c,_=e.a*o+i.a*h+t.a*l+s.a*c;return new N(d,u,f,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new N;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*s.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*s.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*s.b,n.a=6*(a-r)*e.a+(3*a-4*r+1)*t.a+6*(-a+r)*i.a+(3*a-2*r)*s.a}static FromColor3(e,t=1){return new N(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new N(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 N(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew N(0,0,0,0))),d("BABYLON.Color3",L),d("BABYLON.Color4",N);var U=i(504),k=i(137);class V{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,r=!1,n=!1,a=!1,o,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=n,this._divisor=o||1,this._label=h,t instanceof U.n?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,s,r,n=!1,a){const o=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=s?n?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new G(this._engine,this,e,this._updatable,!0,h,void 0===r?this._instanced:r,o,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));k.V.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,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),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class G{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;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,r,n,a,o,h,l,c=!1,d=!1,u=1,f=!1){this._isDisposed=!1;let _=!1;if(this.engine=e,"object"==typeof s&&null!==s?(_=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,a=s.instanced,o=s.offset,h=s.size,l=s.type,c=s.normalized??!1,d=s.useBytes??!1,u=s.divisor??1,f=s.takeBufferOwnership??!1,this._label=s.label):_=!!s,t instanceof V?(this._buffer=t,this._ownsBuffer=f):(this._buffer=new V(e,t,_,n,r,a,d,u,this._label),this._ownsBuffer=!0),this.uniqueId=G._Counter++,this._kind=i,void 0===l){const e=this.getData();this.type=e?G.GetDataType(e):G.FLOAT}else this.type=l;const p=G.GetTypeByteLength(this.type);d?(this._size=h||(n?n/p:G.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*p,this.byteOffset=o||0):(this._size=h||n||G.DeduceStride(i),this.byteStride=n?n*p:this._buffer.byteStride||this._size*p,this.byteOffset=(o||0)*p),this.normalized=c,this._instanced=void 0!==a&&a,this._instanceDivisor=a?u: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(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?G.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/G.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/G.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*G.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){G.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case G.UVKind:case G.UV2Kind:case G.UV3Kind:case G.UV4Kind:case G.UV5Kind:case G.UV6Kind:return 2;case G.NormalKind:case G.PositionKind:return 3;case G.ColorKind:case G.ColorInstanceKind:case G.MatricesIndicesKind:case G.MatricesIndicesExtraKind:case G.MatricesWeightsKind:case G.MatricesWeightsExtraKind:case G.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?G.BYTE:e instanceof Uint8Array?G.UNSIGNED_BYTE:e instanceof Int16Array?G.SHORT:e instanceof Uint16Array?G.UNSIGNED_SHORT:e instanceof Int32Array?G.INT:e instanceof Uint32Array?G.UNSIGNED_INT:G.FLOAT}static GetTypeByteLength(e){switch(e){case G.BYTE:case G.UNSIGNED_BYTE:return 1;case G.SHORT:case G.UNSIGNED_SHORT:return 2;case G.INT:case G.UNSIGNED_INT:case G.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,a,o){if(e instanceof Array){let r=t/4;const a=i/4;for(let t=0;ta[t]=e)),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==l){if(e instanceof Array){const t=s/4;return e.slice(t,t+l)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,l);{let t=e.byteOffset+s;if(o){const i=new Float32Array(l),s=new Float32Array(e.buffer,t,l);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,l)}}return o?e.slice():e}}function z(e,t,i,s){var r,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,s);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(n<3?r(a):n>3?r(t,i,a):r(t,i))||a);return n>3&&a&&Object.defineProperty(t,i,a),a}G._Counter=0,G.BYTE=5120,G.UNSIGNED_BYTE=5121,G.SHORT=5122,G.UNSIGNED_SHORT=5123,G.INT=5124,G.UNSIGNED_INT=5125,G.FLOAT=5126,G.PositionKind="position",G.NormalKind="normal",G.TangentKind="tangent",G.UVKind="uv",G.UV2Kind="uv2",G.UV3Kind="uv3",G.UV4Kind="uv4",G.UV5Kind="uv5",G.UV6Kind="uv6",G.ColorKind="color",G.ColorInstanceKind="instanceColor",G.MatricesIndicesKind="matricesIndices",G.MatricesWeightsKind="matricesWeights",G.MatricesIndicesExtraKind="matricesIndicesExtra",G.MatricesWeightsExtraKind="matricesWeightsExtra",Object.create,Object.create;const W={},X={};function H(e){const t=e.getClassName();if(W[t])return W[t];W[t]={};const i=W[t];let s=e,r=t;for(;r;){const e=X[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function K(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return X[t]||(X[t]={}),X[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function Y(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function q(e){return K(0,e)}function j(e){return K(1,e)}function Z(e){return K(2,e)}function Q(e){return K(3,e)}function $(e){return K(4,e)}function J(e){return K(5,e)}function ee(e){return K(6,e)}function te(e){return K(8,e)}function ie(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}ie.filter=function(e){return(t,i,s)=>ie(t,i,s,e)};var se=i(848),re=i(503);class ne{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),ne._HandleParenthesisContent(e,t)))):ne._HandleParenthesisContent(e,t))||"false"!==e&&ne.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=ne._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class ae{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>ae.HasTags(e),e.addTags=t=>ae.AddTagsTo(e,t),e.removeTags=t=>ae.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>ae.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 e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){ae._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(ae.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!ae.HasTags(e))return;const i=t.split(" ");for(const t in i)ae._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?ae.HasTags(e):ne.Eval(t,(t=>ae.HasTags(e)&&e._tags[t])))}}const oe=function(e,t,i,s={}){const r=e();ae&&ae.HasTags(t)&&ae.AddTagsTo(r,ae.GetTags(t,!0));const n=H(r),a={};for(const e in n){const o=n[e],h=t[e],l=o.type;if(null!=h&&("uniqueId"!==e||he.AllowLoadingUniqueId))switch(l){case 0:case 6:case 11:r[e]=h;break;case 1:s.cloneTexturesOnlyOnce&&a[h.uniqueId]?r[e]=a[h.uniqueId]:(r[e]=i||h.isRenderTarget?h:h.clone(),a[h.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?h:h.clone()}}return r};class he{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw(0,re.n)("ImageProcessingConfiguration")},he._FresnelParametersParser=e=>{throw(0,re.n)("FresnelParameters")},he._ColorCurvesParser=e=>{throw(0,re.n)("ColorCurves")},he._TextureParser=(e,t,i)=>{throw(0,re.n)("Texture")};class le{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new se.cP,this._onClonedObservable=new se.cP}}class ce{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(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||!!this._parentNode&&this._parentNode.doNotSerialize}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&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(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(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){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 le,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new se.cP,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=y.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new se.cP,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||_.q.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-1!==this._behaviors.indexOf(e)||(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-1===t||(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&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&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!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),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||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew ce(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw(0,re.n)("AnimationRange")},ce._NodeConstructors={},z([q()],ce.prototype,"name",void 0),z([q()],ce.prototype,"id",void 0),z([q()],ce.prototype,"uniqueId",void 0),z([q()],ce.prototype,"state",void 0),z([q()],ce.prototype,"metadata",void 0);var de=i(790);const ue=(e,t,i)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class fe{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const a of n){if("_"===a[0]&&(!s||-1===s.indexOf(a)))continue;if(a.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(a))continue;const n=e[a],o=typeof n;if("function"!==o)try{if("object"===o)if(n instanceof Uint8Array)t[a]=Uint8Array.from(n);else if(n instanceof Array){if(t[a]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e0||pe.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in pe.CustomRequestHeaders){const t=pe.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return pe.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){pe.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of pe.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).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)}}pe.CustomRequestHeaders={},pe.CustomRequestModifiers=new Array,pe.SkipRequestModificationForBabylonCDN=!0;class ge{}ge.FilesToLoad={};class me extends Error{}me._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Te=3e3;class xe extends me{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",me._setPrototypeOf(this,xe.prototype)}}const Ee=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,a,o,h,l="",c=0;const d=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,a=(3&i)<<4|s>>4,o=(15&s)<<2|r>>6,h=63&r,isNaN(s)?o=h=64:isNaN(r)&&(h=64),l+=t.charAt(n)+t.charAt(a)+t.charAt(o)+t.charAt(h);return l},ve=e=>atob(e);var Ae=i(125);class Me{static SetImmediate(e){(0,de.BA)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}var be=i(741);const Se=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class ye extends xe{constructor(e,t){super(e,4e3),this.name="LoadFileError",me._setPrototypeOf(this,ye.prototype),t instanceof pe?this.request=t:this.file=t}}class Ie extends xe{constructor(e,t){super(e,4001),this.request=t,this.name="RequestFileError",me._setPrototypeOf(this,Ie.prototype)}}class Re extends xe{constructor(e,t){super(e,4002),this.file=t,this.name="ReadFileError",me._setPrototypeOf(this,Re.prototype)}}const Ce={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},Pe=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&Ce.CorsBehavior)if("string"==typeof Ce.CorsBehavior||Ce.CorsBehavior instanceof String)t.crossOrigin=Ce.CorsBehavior;else{const i=Ce.CorsBehavior(e);i&&(t.crossOrigin=i)}},De=(e,t,i,s,r="",n)=>{const a=_.q.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!a?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let o,h=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:r})),h=!0):o=`data:${r};base64,`+Ee(e):e instanceof Blob?(o=URL.createObjectURL(e),h=!0):(o=Ce.CleanUrl(e),o=Ce.PreprocessUrl(e));const l=t=>{if(i){const s=o||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(a?._features.forceBitmapOverHTMLImageElement)return Fe(o,(s=>{a.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),h&&URL.revokeObjectURL(o)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{l(t)})),null;const c=new Image;Pe(o,c);const d=[],u=()=>{d.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),d.length=0};d.push({target:c,name:"load",handler:()=>{u(),t(c),h&&c.src&&URL.revokeObjectURL(c.src)}}),d.push({target:c,name:"error",handler:e=>{u(),l(e),h&&c.src&&URL.revokeObjectURL(c.src)}}),d.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;u();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);_.q.UseFallbackTexture=!1,l(t),h&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),d.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const f="blob:"===o.substring(0,5),p="data:"===o.substring(0,5),g=()=>{f||p||!pe.IsCustomRequestAvailable?c.src=o:Fe(o,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);h=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{l(t)}))};if(!f&&!p&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(o,c)}),g);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(ge.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(ge.FilesToLoad[e])}catch(i){t=URL.createObjectURL(ge.FilesToLoad[e])}c.src=t,h=!0}catch(e){c.src=""}return c}}g()}return c},Oe=(e,t,i,s,r)=>{const n=new FileReader,a={onCompleteObservable:new se.cP,abort:()=>n.abort()};return n.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(n.onerror=()=>{r(new Re(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),a},Fe=(e,t,i,s,r,n,a)=>{if(e.name)return Oe(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const o=e;if(-1!==o.indexOf("file:")){let e=decodeURIComponent(o.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=ge.FilesToLoad[e];if(s)return Oe(s,t,i,r,n?e=>n(void 0,new ye(e.message,e.file)):void 0)}const{match:h,type:l}=Be(o);if(h){const e={onCompleteObservable:new se.cP,abort:()=>()=>{}};try{const e=r?Ue(o):ke(o);t(e,void 0,l)}catch(e){n?n(void 0,e):k.V.Error(e.message||"Failed to parse the Data URL")}return Me.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return we(o,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new ye(e.message,e.request))}:void 0,a)},we=(e,t,i,s,r,n,a)=>{e=Ce.CleanUrl(e),e=Ce.PreprocessUrl(e);const o=Ce.BaseUrl+e;let h=!1;const l={onCompleteObservable:new se.cP,abort:()=>h=!0},c=()=>{let e,s=new pe,c=null;const d=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",u))};let u=()=>{d(),l.onCompleteObservable.notifyObservers(l),l.onCompleteObservable.clear(),i=void 0,e=null,u=null,n=void 0,a=void 0,t=void 0};l.abort=()=>{h=!0,u&&u(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const f=e=>{const t=e.message||"Unknown error";n&&s?n(new Ie(t,s)):k.V.Error(t)},_=l=>{if(s){if(s.open("GET",o),a)try{a(s)}catch(e){return void f(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),u&&s.addEventListener("loadend",u),e=()=>{if(!h&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!(0,de.BA)()||Le())){try{t&&t(r?s.response:s.responseText,s)}catch(e){f(e)}return}const i=Ce.DefaultRetryStrategy;if(i){const e=i(o,s,l);if(-1!==e)return d(),s=new pe,void(c=setTimeout((()=>_(l+1)),e))}const a=new Ie("Error status: "+s.status+" "+s.statusText+" - Unable to load "+o,s);n&&n(a)}},s.addEventListener("readystatechange",e),s.send()}};_(0)};if(s&&s.enableSceneOffline){const a=e=>{e&&e.status>400?n&&n(e):c()},o=()=>{s&&s.loadFile(Ce.BaseUrl+e,(e=>{!h&&t&&t(e),l.onCompleteObservable.notifyObservers(l)}),i?e=>{!h&&i&&i(e)}:void 0,a,r)};s.open(o,a)}else c();return l},Le=()=>"undefined"!=typeof location&&"file:"===location.protocol,Ne=e=>Se.test(e),Be=e=>{const t=Se.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Ue(e){return(e=>{const t=ve(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;eve(e.split(",")[1]);let Ve;s.$._FileToolsLoadImage=De,be.sg.loadFile=Fe,Ae.J.loadFile=Fe,((e,t,i,s,r,n,a,o,h,l)=>{Ve={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:a,ReadFile:o,RequestFile:h,SetCorsBehavior:l},Object.defineProperty(Ve,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Ve,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Ve,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Ve,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(Ue,ke,Ce,Ne,Le,Fe,De,Oe,we,Pe);class Ge{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=u(e);if(t)return t;k.V.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}Ge.RegisteredExternalClasses={};var We=i(597);class Xe{static get BaseUrl(){return Ce.BaseUrl}static set BaseUrl(e){Ce.BaseUrl=e}static get CleanUrl(){return Ce.CleanUrl}static set CleanUrl(e){Ce.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){Fe(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Xe.ScriptBaseUrl&&e.startsWith(Xe._DefaultCdnUrl)){const t="/"===Xe.ScriptBaseUrl[Xe.ScriptBaseUrl.length-1]?Xe.ScriptBaseUrl.substring(0,Xe.ScriptBaseUrl.length-1):Xe.ScriptBaseUrl;e=e.replace(Xe._DefaultCdnUrl,t)}return e=Xe.ScriptPreprocessUrl(e),t&&(e=Xe.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Xe.GetBabylonScriptURL(e),Xe.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Xe.GetBabylonScriptURL(e),Xe.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!(0,de.BA)())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new se.cP,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return Oe(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){fe.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 s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}Xe.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(Xe._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&Xe.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)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"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,a){throw(0,re.n)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw(0,re.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,a=!1,o,h=!1,l=!1,c=!0,d){throw(0,re.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,a,o=!1,h=!1,l=!0,c){throw(0,re.n)("ScreenshotTools")}static RandomId(){return ze()}static IsBase64(e){return Ne(e)}static DecodeBase64(e){return Ue(e)}static get errorsCount(){return k.V.errorsCount}static Log(e){k.V.Log(e)}static Warn(e){k.V.Warn(e)}static Error(e){k.V.Error(e)}static get LogCache(){return k.V.LogCache}static ClearLogCache(){k.V.ClearLogCache()}static set LogLevels(e){k.V.LogLevels=e}static set PerformanceLogLevel(e){return(e&Xe.PerformanceUserMarkLogLevel)===Xe.PerformanceUserMarkLogLevel?(Xe.StartPerformanceCounter=Xe._StartUserMark,void(Xe.EndPerformanceCounter=Xe._EndUserMark)):(e&Xe.PerformanceConsoleLogLevel)===Xe.PerformanceConsoleLogLevel?(Xe.StartPerformanceCounter=Xe._StartPerformanceConsole,void(Xe.EndPerformanceCounter=Xe._EndPerformanceConsole)):(Xe.StartPerformanceCounter=Xe._StartPerformanceCounterDisabled,void(Xe.EndPerformanceCounter=Xe._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Xe._Performance){if(!(0,de.BA)())return;Xe._Performance=window.performance}t&&Xe._Performance.mark&&Xe._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Xe._Performance.mark&&(Xe._Performance.mark(e+"-End"),Xe._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Xe._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Xe._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return _e.j.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!(0,de.XD)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Xe.UseCustomRequestHeaders=!1,Xe.CustomRequestHeaders=pe.CustomRequestHeaders,Xe.GetDOMTextContent=de.Zl,Xe._DefaultCdnUrl="https://cdn.babylonjs.com",Xe.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Xe.NoneLogLevel=k.V.NoneLogLevel,Xe.MessageLogLevel=k.V.MessageLogLevel,Xe.WarningLogLevel=k.V.WarningLogLevel,Xe.ErrorLogLevel=k.V.ErrorLogLevel,Xe.AllLogLevel=k.V.AllLogLevel,Xe.IsWindowObjectExist=de.BA,Xe.PerformanceNoneLogLevel=0,Xe.PerformanceUserMarkLogLevel=1,Xe.PerformanceConsoleLogLevel=2,Xe.StartPerformanceCounter=Xe._StartPerformanceCounterDisabled,Xe.EndPerformanceCounter=Xe._EndPerformanceCounterDisabled;class He{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(a),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}Xe.Mix=We.zF,Xe.IsExponentOfTwo=We.L8,_.q.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";var Ke=i(321),Ye=i(329);Ke.w.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new Ye.A(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Ke.w.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new Ye.A(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Ke.w.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},Ke.w.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Ke.w.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Ke.w.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class qe{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(qe._UpdatedUbosInFrame[this._name]||(qe._UpdatedUbosInFrame[this._name]=0),qe._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,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(void 0===s){if(this._buffer)return void k.V.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||0!==this.includeOnlyWithLayerMask&&0==(this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._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=Ze.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=he.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=he.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)}))),he.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return ce.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=Ze.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=he.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);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)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===Ze.INTENSITYMODE_AUTOMATIC&&(i=t===Ze.LIGHTTYPEID_DIRECTIONALLIGHT?Ze.INTENSITYMODE_ILLUMINANCE:Ze.INTENSITYMODE_LUMINOUSINTENSITY),t){case Ze.LIGHTTYPEID_POINTLIGHT:case Ze.LIGHTTYPEID_SPOTLIGHT:switch(i){case Ze.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Ze.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Ze.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Ze.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Ze.INTENSITYMODE_ILLUMINANCE:e=1;break;case Ze.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case Ze.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Ze.FALLOFF_DEFAULT=je.FALLOFF_DEFAULT,Ze.FALLOFF_PHYSICAL=je.FALLOFF_PHYSICAL,Ze.FALLOFF_GLTF=je.FALLOFF_GLTF,Ze.FALLOFF_STANDARD=je.FALLOFF_STANDARD,Ze.LIGHTMAP_DEFAULT=je.LIGHTMAP_DEFAULT,Ze.LIGHTMAP_SPECULAR=je.LIGHTMAP_SPECULAR,Ze.LIGHTMAP_SHADOWSONLY=je.LIGHTMAP_SHADOWSONLY,Ze.INTENSITYMODE_AUTOMATIC=je.INTENSITYMODE_AUTOMATIC,Ze.INTENSITYMODE_LUMINOUSPOWER=je.INTENSITYMODE_LUMINOUSPOWER,Ze.INTENSITYMODE_LUMINOUSINTENSITY=je.INTENSITYMODE_LUMINOUSINTENSITY,Ze.INTENSITYMODE_ILLUMINANCE=je.INTENSITYMODE_ILLUMINANCE,Ze.INTENSITYMODE_LUMINANCE=je.INTENSITYMODE_LUMINANCE,Ze.LIGHTTYPEID_POINTLIGHT=je.LIGHTTYPEID_POINTLIGHT,Ze.LIGHTTYPEID_DIRECTIONALLIGHT=je.LIGHTTYPEID_DIRECTIONALLIGHT,Ze.LIGHTTYPEID_SPOTLIGHT=je.LIGHTTYPEID_SPOTLIGHT,Ze.LIGHTTYPEID_HEMISPHERICLIGHT=je.LIGHTTYPEID_HEMISPHERICLIGHT,z([Z()],Ze.prototype,"diffuse",void 0),z([Z()],Ze.prototype,"specular",void 0),z([q()],Ze.prototype,"falloffType",void 0),z([q()],Ze.prototype,"intensity",void 0),z([q()],Ze.prototype,"range",null),z([q()],Ze.prototype,"intensityMode",null),z([q()],Ze.prototype,"radius",null),z([q()],Ze.prototype,"_renderPriority",void 0),z([Y("_reorderLightsInScene")],Ze.prototype,"renderPriority",void 0),z([q("shadowEnabled")],Ze.prototype,"_shadowEnabled",void 0),z([q("excludeWithLayerMask")],Ze.prototype,"_excludeWithLayerMask",void 0),z([q("includeOnlyWithLayerMask")],Ze.prototype,"_includeOnlyWithLayerMask",void 0),z([q("lightmapMode")],Ze.prototype,"_lightmapMode",void 0);class Qe{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^(0|this.height),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 Qe(this.width*e,this.height*t)}clone(){return new Qe(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Qe(0,0)}add(e){return new Qe(this.width+e.width,this.height+e.height)}subtract(e){return new Qe(this.width-e.width,this.height-e.height)}scale(e){return new Qe(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new Qe(s,r)}}class $e{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}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}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=Qe.Zero(),this._cachedBaseSize=Qe.Zero(),this._initialSamplingMode=2,this._texture=$e._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}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._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):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,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 Je extends $e{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.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}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.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}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=ze()),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=Je.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 se.cP,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Je._IsScene(e)?this._scene=e:this._engine=e:this._scene=_.q.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 y.IdentityReadOnly}getReflectionTextureMatrix(){return y.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!r,t),h=a.getLoadedTexturesCache();for(let a=0;a=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,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=he.Serialize(this);return he.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}Je.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,z([q()],Je.prototype,"uniqueId",void 0),z([q()],Je.prototype,"name",void 0),z([q()],Je.prototype,"metadata",void 0),z([q("hasAlpha")],Je.prototype,"_hasAlpha",void 0),z([q("getAlphaFromRGB")],Je.prototype,"_getAlphaFromRGB",void 0),z([q()],Je.prototype,"level",void 0),z([q("coordinatesIndex")],Je.prototype,"_coordinatesIndex",void 0),z([q()],Je.prototype,"optimizeUVAllocation",void 0),z([q("coordinatesMode")],Je.prototype,"_coordinatesMode",void 0),z([q()],Je.prototype,"wrapU",null),z([q()],Je.prototype,"wrapV",null),z([q()],Je.prototype,"wrapR",void 0),z([q()],Je.prototype,"anisotropicFilteringLevel",void 0),z([q()],Je.prototype,"isCube",null),z([q()],Je.prototype,"is3D",null),z([q()],Je.prototype,"is2DArray",null),z([q()],Je.prototype,"gammaSpace",null),z([q()],Je.prototype,"invertZ",void 0),z([q()],Je.prototype,"lodLevelInAlpha",void 0),z([q()],Je.prototype,"lodGenerationOffset",null),z([q()],Je.prototype,"lodGenerationScale",null),z([q()],Je.prototype,"linearSpecularLOD",null),z([j()],Je.prototype,"irradianceTexture",null),z([q()],Je.prototype,"isRenderTarget",void 0);class et{constructor(e,t,i,s){this.normal=new M(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new et(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^(0|this.d),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 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=et._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,o=s*i[0]+r*i[1]+n*i[2]+a*i[3],h=s*i[4]+r*i[5]+n*i[6]+a*i[7],l=s*i[8]+r*i[9]+n*i[10]+a*i[11],c=s*i[12]+r*i[13]+n*i[14]+a*i[15];return new et(o,h,l,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,a=i.x-e.x,o=i.y-e.y,h=i.z-e.z,l=r*h-n*o,c=n*a-s*h,d=s*o-r*a,u=Math.sqrt(l*l+c*c+d*d);let f;return f=0!==u?1/u:0,this.normal.x=l*f,this.normal.y=c*f,this.normal.z=d*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return M.Dot(this.normal,e)<=t}signedDistanceTo(e){return M.Dot(e,this.normal)+this.d}static FromArray(e){return new et(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new et(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new et(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 M.Dot(i,t)+s}}function tt(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const a=n.getContext("2d");if(!a)return null;const o=a.createImageData(s,r);if(o.data.set(e),a.putImageData(o,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}et._TmpMatrix=y.Identity();class it{}it.UseOpenGLOrientationForUV=!1;class st extends Je{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=st.TRILINEAR_SAMPLINGMODE,a={},o,h=5){throw(0,re.n)("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,r=st.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,h=!1,l,c,d,u,f){let _;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 se.cP,this._isBlocking=!0,this.name=e||"",this.url=e;let p=!1,g=null,m=!0;"object"==typeof i&&null!==i?(_=i.noMipmap??!1,s=i.invertY??!it.UseOpenGLOrientationForUV,r=i.samplingMode??st.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,a=i.onError??null,o=i.buffer??null,h=i.deleteBuffer??!1,l=i.format,c=i.mimeType,d=i.loaderOptions,u=i.creationFlags,p=i.useSRGBBuffer??!1,g=i.internalTexture??null,m=i.gammaSpace??m):_=!!i,this._gammaSpace=m,this._noMipmap=_,this._invertY=void 0===s?!it.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=o,this._deleteBuffer=h,this._mimeType=c,this._loaderOptions=d,this._creationFlags=u,this._useSRGBBuffer=p,this._forcedExtension=f,l&&(this._format=l);const T=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const E=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&T&&T.resetCachedMaterial()},v=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),st.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!g)return this._delayedOnLoad=E,void(this._delayedOnError=v);if(this._texture=g??this._getFromCache(this.url,_,r,this._invertY,p,this.isCube),this._texture)if(this._texture.isReady)Me.SetImmediate((()=>E()));else{const e=this._texture.onLoadedObservable.add(E);this._texture.onErrorObservable.add((t=>{v(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(T&&T.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=E,this._delayedOnError=v;else{try{this._texture=x.createTexture(this.url,_,this._invertY,T,r,E,v,this._buffer,void 0,this._format,this._forcedExtension,c,d,u,p)}catch(e){throw v("error loading",e),e}h&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.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(4!==this.delayLoadState)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?Me.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,M.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=y.Zero(),this._rowGenerationMatrix=new y,this._t0=M.Zero(),this._t1=M.Zero(),this._t2=M.Zero()),y.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(y.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,R.Matrix[0]),y.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,R.Matrix[1]),y.ScalingToRef(this._cachedUScale,this._cachedVScale,0,R.Matrix[2]),y.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,R.Matrix[3]),R.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(R.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(R.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(R.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),y.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,(e=>e.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!==st.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=y.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=y.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 st.PLANAR_MODE:y.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 st.PROJECTION_MODE:{y.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:y.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.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 he.Clone((()=>new st(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;st.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(st._SerializeInternalTextureUniqueId);return t?((st.SerializeBuffers||st.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(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,"+Ee(this._buffer):(st.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?tt(r,e.getSize(),s.invertY):null}(this):async function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?tt(r,e.getSize(),s.invertY):null}(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,st._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=Ge.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return st._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=st._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=et.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(a)}),e._creationFlags??0,e._useSRGBBuffer??!1),a.name=e.name;else{let o;o=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||st.UseSerializedUrlIfAny)&&(o=e.url);const h={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(a)},internalTexture:r};a=new st(o,t,h)}return a}}),e,t)}static CreateFromBase64String(e,t,i,s,r,n=st.TRILINEAR_SAMPLINGMODE,a=null,o=null,h=5,l,c){return new st("data:"+t,i,s,r,n,a,o,e,!1,h,void 0,void 0,l,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,a=st.TRILINEAR_SAMPLINGMODE,o=null,h=null,l=5,c,d){return"data:"!==e.substr(0,5)&&(e="data:"+e),new st(e,i,r,n,a,o,h,t,s,l,void 0,void 0,c,d)}}st.SerializeBuffers=!0,st.ForceSerializeBuffers=!1,st.OnTextureLoadErrorObservable=new se.cP,st._SerializeInternalTextureUniqueId=!1,st._CubeTextureParser=(e,t,i)=>{throw(0,re.n)("CubeTexture")},st._CreateMirror=(e,t,i,s)=>{throw(0,re.n)("MirrorTexture")},st._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw(0,re.n)("RenderTargetTexture")},st.NEAREST_SAMPLINGMODE=1,st.NEAREST_NEAREST_MIPLINEAR=8,st.BILINEAR_SAMPLINGMODE=2,st.LINEAR_LINEAR_MIPNEAREST=11,st.TRILINEAR_SAMPLINGMODE=3,st.LINEAR_LINEAR_MIPLINEAR=3,st.NEAREST_NEAREST_MIPNEAREST=4,st.NEAREST_LINEAR_MIPNEAREST=5,st.NEAREST_LINEAR_MIPLINEAR=6,st.NEAREST_LINEAR=7,st.NEAREST_NEAREST=1,st.LINEAR_NEAREST_MIPNEAREST=9,st.LINEAR_NEAREST_MIPLINEAR=10,st.LINEAR_LINEAR=2,st.LINEAR_NEAREST=12,st.EXPLICIT_MODE=0,st.SPHERICAL_MODE=1,st.PLANAR_MODE=2,st.CUBIC_MODE=3,st.PROJECTION_MODE=4,st.SKYBOX_MODE=5,st.INVCUBIC_MODE=6,st.EQUIRECTANGULAR_MODE=7,st.FIXED_EQUIRECTANGULAR_MODE=8,st.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,st.CLAMP_ADDRESSMODE=0,st.WRAP_ADDRESSMODE=1,st.MIRROR_ADDRESSMODE=2,st.UseSerializedUrlIfAny=!1,z([q()],st.prototype,"url",void 0),z([q()],st.prototype,"uOffset",void 0),z([q()],st.prototype,"vOffset",void 0),z([q()],st.prototype,"uScale",void 0),z([q()],st.prototype,"vScale",void 0),z([q()],st.prototype,"uAng",void 0),z([q()],st.prototype,"vAng",void 0),z([q()],st.prototype,"wAng",void 0),z([q()],st.prototype,"uRotationCenter",void 0),z([q()],st.prototype,"vRotationCenter",void 0),z([q()],st.prototype,"wRotationCenter",void 0),z([q()],st.prototype,"homogeneousRotationInUVTransform",void 0),z([q()],st.prototype,"isBlocking",null),d("BABYLON.Texture",st),he._TextureParser=st.Parse;class rt{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[G.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[G.PositionKind]=new G(this._scene.getEngine(),e,G.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[G.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const a=this._scene.getEngine();for(let o=0;onull!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let o=0,h=s.length;othis.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}nt._GlobalId=0;class at extends nt{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||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));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){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(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(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]: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=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.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(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==ct.G.Depth&&n!==ct.G.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const a=[],o=[],h=[],l=[],c=[],d=[],u=[],f={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,s)}n._bindUnboundFramebuffer(a)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===a.format?d=i.DEPTH_COMPONENT16:16===a.format?d=i.DEPTH_COMPONENT24:17===a.format||13===a.format?d=i.DEPTH24_STENCIL8:14===a.format?d=i.DEPTH_COMPONENT32F:18===a.format&&(d=i.DEPTH32F_STENCIL8)),a.is2DArray?i.texImage3D(n,0,d,a.width,a.height,s,0,c,l,null):a.is3D?i.texImage3D(n,0,d,a.width,a.height,r,0,c,l,null):i.texImage2D(n,0,d,a.width,a.height,0,c,l,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),a},Ke.w.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},Ke.w.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new ct.h(this,ct.G.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const a=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,k.V.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i};class ft{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new ft(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 ft(this.x,this.y,this.width,this.height)}}var _t=i(420);class pt{static GetEffect(e){return void 0===e.getPipelineContext?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){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}var gt=i(610);gt.l.ShadersStore.postprocessVertexShader="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}";const mt={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Tt{constructor(e,t=mt){this._fullscreenViewport=new ft(0,0,1,1);const i=t.positions??mt.positions,s=t.indices??mt.indices;this.engine=e,this._vertexBuffers={[G.PositionKind]:new G(e,i,G.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._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 void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?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[G.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[G.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class xt{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new se.cP;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new pt(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new _t.M(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Et="passPixelShader",vt="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";gt.l.ShadersStore[Et]=vt;const At=Et,Mt=vt;class bt{static _CreateDumpRenderer(){if(!bt._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Ke.w(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new Ke.w(e,!1,i)}_.q.Instances.pop(),_.q.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&t.dispose()})),t.getCaps().parallelShaderCompile=void 0;const s=new Tt(t),r=new xt({engine:t,name:At,fragmentShader:Mt,samplerNames:["textureSampler"]});bt._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return bt._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,a){const o=await i.readPixels(0,0,e,t),h=new Uint8Array(o.buffer);bt.DumpData(e,t,h,s,r,n,!0,void 0,a)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,a=!1,o){return new Promise((h=>{bt.DumpData(e,t,i,(e=>h(e)),s,r,n,a,o)}))}static DumpData(e,t,i,s,r="image/png",n,a=!1,o=!1,h){const l=bt._CreateDumpRenderer();if(l.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*P.Clamp(s))}i=e}const c=l.engine.createRawTexture(i,e,t,5,!1,!a,1);l.renderer.setViewport(),l.renderer.applyEffectWrapper(l.wrapper),l.wrapper.effect._bindTexture("textureSampler",c),l.renderer.draw(),o?Xe.ToBlob(l.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,h):Xe.EncodeScreenshotCanvasData(l.canvas,s,r,n,h),c.dispose()}static Dispose(){bt._DumpToolsEngine&&(bt._DumpToolsEngine.wrapper.dispose(),bt._DumpToolsEngine.renderer.dispose(),bt._DumpToolsEngine.engine.dispose()),bt._DumpToolsEngine=null}}Xe.DumpData=bt.DumpData,Xe.DumpDataAsync=bt.DumpDataAsync,Xe.DumpFramebuffer=bt.DumpFramebuffer;class St extends st{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=l(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new se.cP,this.onAfterUnbindObservable=new se.cP,this.onBeforeRenderObservable=new se.cP,this.onAfterRenderObservable=new se.cP,this.onClearObservable=new se.cP,this.onResizeObservable=new se.cP,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=M.Zero(),!(i=this.getScene()))return;const x=this.getScene().getEngine();this._gammaSpace=T,this._coordinatesMode=st.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new lt(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:l,samples:f,creationFlags:_,noColorAttachment:p,useSRGBBuffer:g,colorAttachment:m,label:this.name},this.samplingMode===st.NEAREST_SAMPLINGMODE&&(this.wrapU=st.CLAMP_ADDRESSMODE,this.wrapV=st.CLAMP_ADDRESSMODE),u||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=st.INVCUBIC_MODE,this._textureMatrix=y.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==f&&(this.samples=f)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||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){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const a=n.getEngine();if(a._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(a.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(a.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),a.snapshotRendering&&1===a.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let o=null;const h=this.renderList?this.renderList:n.getActiveMeshes().data,l=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(o=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,h,l)),o?this._prepareRenderingManager(o,o.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(h,l,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),o=h);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,o,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&bt.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a)}this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&5===e&&a.generateMipMapsForCubemap(this._texture,!0),a._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new St(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 i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===St.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=St.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}St.REFRESHRATE_RENDER_ONCE=0,St.REFRESHRATE_RENDER_ONEVERYFRAME=1,St.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,st._CreateRenderTargetTexture=(e,t,i,s,r)=>new St(e,t,i,s);var yt=i(662);class It{static RegisterShaderCodeProcessing(e,t){t?It._CustomShaderCodeProcessing[e??""]=t:delete It._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return It._CustomShaderCodeProcessing[e]??It._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,a=1,o,h,l=null,c=0,d="postprocess",u,f=!1,_=5,p=yt.w.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new nt(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new A(1,1),this._texelSize=A.Zero(),this.onActivateObservable=new se.cP,this.onSizeChangedObservable=new se.cP,this.onApplyObservable=new se.cP,this.onBeforeRenderObservable=new se.cP,this.onAfterRenderObservable=new se.cP,this.name=e;let g=1,m=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,g=e.size??1,n=e.camera??null,a=e.samplingMode??1,o=e.engine,h=e.reusable,l=e.defines??null,c=e.textureType??0,d=e.vertexUrl??"postprocess",u=e.indexParameters,f=e.blockCompilation??!1,_=e.textureFormat??5,p=e.shaderLanguage??yt.w.GLSL,m=e.uniformBuffers??null}else r&&(g="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=g,this.renderTargetSamplingMode=a||1,this._reusable=h||!1,this._textureType=c,this._textureFormat=_,this._shaderLanguage=p,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=m||[],this._indexParameters=u,this._drawWrapper=new pt(this._engine),f||this.updateEffect(l)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new nt(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,a,o){const h=It._GetShaderCodeProcessing(this.name);if(h?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=h.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:a??this._vertexUrl,fragment:o??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:h?.processCodeAfterIncludes?(e,t)=>h.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:h?.processFinalCode?(e,t)=>h.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(a/h,o/l),this._engine.bindFramebuffer(d,0,a,o,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),It._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(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)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=he.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=It.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=u(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return he.Parse((()=>new It(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)}}It._CustomShaderCodeProcessing={},z([q()],It.prototype,"uniqueId",void 0),z([q()],It.prototype,"name",void 0),z([q()],It.prototype,"width",void 0),z([q()],It.prototype,"height",void 0),z([q()],It.prototype,"renderTargetSamplingMode",void 0),z([te()],It.prototype,"clearColor",void 0),z([q()],It.prototype,"autoClear",void 0),z([q()],It.prototype,"forceAutoClearInAlphaMode",void 0),z([q()],It.prototype,"alphaMode",void 0),z([q()],It.prototype,"alphaConstants",void 0),z([q()],It.prototype,"enablePixelPerfectMode",void 0),z([q()],It.prototype,"forceFullscreenViewport",void 0),z([q()],It.prototype,"scaleMode",void 0),z([q()],It.prototype,"alwaysForcePOT",void 0),z([q("samples")],It.prototype,"_samples",void 0),z([q()],It.prototype,"adaptScaleToCurrentViewport",void 0),d("BABYLON.PostProcess",It);gt.l.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";gt.l.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";gt.l.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";gt.l.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";gt.l.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";gt.l.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";gt.l.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Rt extends It{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=st.BILINEAR_SAMPLINGMODE,a,o,h=0,l="",c=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,a,o,null,h,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=l,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],a=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return he.Parse((()=>new Rt(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}z([q("kernel")],Rt.prototype,"_kernel",void 0),z([q("packedFloat")],Rt.prototype,"_packedFloat",void 0),z([$()],Rt.prototype,"direction",void 0),d("BABYLON.BlurPostProcess",Rt);class Ct{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i=0){const e=i.activeCamera;1===e.mode&&k.V.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function Bt(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(wt,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",wt)):i.setColor3("vFogColor",e.fogColor))}function Ut(e,t,i){Lt.NUM_MORPH_INFLUENCERS=i,kt(e,t,Lt)}function kt(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&_.q.LastCreatedEngine){const r=_.q.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const a=n&&n.supportsNormals&&i.NORMAL,o=n&&n.supportsTangents&&i.TANGENT,h=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&k.V.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Vt(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function Gt(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function zt(e,t){t.bindToEffect(e,"Scene")}function Wt(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function Xt(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function Ht(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function Kt(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function Yt(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function qt(e,t,i,s,r,n,a){switch(a.needNormals=!0,void 0===r["LIGHT"+s]&&(a.needRebuild=!0),r["LIGHT"+s]=!0,r["SPOTLIGHT"+s]=!1,r["HEMILIGHT"+s]=!1,r["POINTLIGHT"+s]=!1,r["DIRLIGHT"+s]=!1,i.prepareLightSpecificDefines(r,s),r["LIGHT_FALLOFF_PHYSICAL"+s]=!1,r["LIGHT_FALLOFF_GLTF"+s]=!1,r["LIGHT_FALLOFF_STANDARD"+s]=!1,i.falloffType){case je.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+s]=!0;break;case je.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+s]=!0;break;case je.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+s]=!0}if(n&&!i.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+s]=!1,r["SHADOWCSM"+s]=!1,r["SHADOWCSMDEBUG"+s]=!1,r["SHADOWCSMNUM_CASCADES"+s]=!1,r["SHADOWCSMUSESHADOWMAXZ"+s]=!1,r["SHADOWCSMNOBLEND"+s]=!1,r["SHADOWCSM_RIGHTHANDED"+s]=!1,r["SHADOWPCF"+s]=!1,r["SHADOWPCSS"+s]=!1,r["SHADOWPOISSON"+s]=!1,r["SHADOWESM"+s]=!1,r["SHADOWCLOSEESM"+s]=!1,r["SHADOWCUBE"+s]=!1,r["SHADOWLOWQUALITY"+s]=!1,r["SHADOWMEDIUMQUALITY"+s]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){const t=i.getShadowGenerator(e.activeCamera)??i.getShadowGenerator();if(t){const e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=je.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==je.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function jt(e,t,i,s,r=null,n=!1){r&&r.push("Light"+e),n||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowTexture"+e),i.push("depthTexture"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),s&&(i.push("projectionLightTexture"+e),t.push("textureProjectionMatrix"+e)))}class Zt{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===Zt.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===Zt.FILTER_PCF||e===Zt.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==Zt.FILTER_PCF&&e!==Zt.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===Zt.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Zt.FILTER_POISSONSAMPLING);(e||this.filter===Zt.FILTER_POISSONSAMPLING)&&(this.filter=e?t:Zt.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Zt.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Zt.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Zt.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Zt.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Zt.FILTER_PCF);(e||this.filter===Zt.FILTER_PCF)&&(this.filter=e?t:Zt.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===Zt.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Zt.FILTER_PCSS);(e||this.filter===Zt.FILTER_PCSS)&&(this.filter=e?t:Zt.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return Zt.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new se.cP,this.onAfterShadowMapRenderObservable=new se.cP,this.onBeforeShadowMapRenderMeshObservable=new se.cP,this.onAfterShadowMapRenderMeshObservable=new se.cP,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Zt.FILTER_NONE,this._filteringQuality=Zt.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=M.Zero(),this._viewMatrix=y.Zero(),this._projectionMatrix=y.Zero(),this._transformMatrix=y.Zero(),this._cachedPosition=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=y.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),Zt._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new St(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new St(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=st.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=st.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(st.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===Zt.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Zt.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new N(0,0,0,0),i=new N(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===Zt.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=lt.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new Rt(this._light.name+"KernelBlurY",new A(0,1),this.blurKernel,1,null,st.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new It(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,st.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(l,"Mesh"),s.transferToEffect(e?t:f)):(i.getMeshUniformBuffer().bindToEffect(l,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,a.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(l),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===Zt.FILTER_NONE||this.filter===Zt.FILTER_PCSS?this._shadowMap.updateSamplingMode(st.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(st.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let a=0;const o=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[a],i.useInstances,n[a].getMaterial()?.needAlphaBlendingForMesh(n[a].getMesh())??!1);)if(a++,a>=n.length)return void(e&&e(this));setTimeout(o,16)}};o()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(G.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Ze.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,a=i.defines;const o=[G.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(G.NormalKind)&&(o.push(G.NormalKind),n.push("#define NORMAL"),h.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const l=s.needAlphaTesting();if((l||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??Zt.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),l&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(G.UVKind)&&(o.push(G.UVKind),n.push("#define UV1")),h.isVerticesDataPresent(G.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(o.push(G.UV2Kind),n.push("#define UV2"))}const c=new Ct;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){o.push(G.MatricesIndicesKind),o.push(G.MatricesWeightsKind),h.numBoneInfluencers>4&&(o.push(G.MatricesIndicesExtraKind),o.push(G.MatricesWeightsExtraKind));const e=h.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const d=h.morphTargetManager;let u=0;if(d&&(u=d.numMaxInfluencers||d.numInfluencers,u>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+u),d.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),Ut(o,h,u))),Dt(s,this._scene,n),t&&(n.push("#define INSTANCES"),Vt(o),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const f=h.bakedVertexAnimationManager;t&&f&&f.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),o.push("bakedVertexAnimationSettingsInstanced"));const _=n.join("\n");if(a!==_){a=_;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(Pt(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===o.indexOf(e)&&o.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const h=this._scene.getEngine();r=h.createEffect(e,{attributes:o,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:_,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:u}},h),i.setEffect(r,a)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Zt.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Zt.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Zt.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Zt.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===Zt.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Zt.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),M.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(M.Dot(this._lightDirection,M.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),y.LookAtLHToRef(t,t.add(this._lightDirection),M.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw(0,re.n)("ShadowGeneratorSceneComponent")};class Qt{constructor(e,t,i){this.vectors=o.BuildArray(8,M.Zero),this.center=M.Zero(),this.centerWorld=M.Zero(),this.extendSize=M.Zero(),this.extendSizeWorld=M.Zero(),this.directions=o.BuildArray(3,M.Zero),this.vectorsWorld=o.BuildArray(8,M.Zero),this.minimumWorld=M.Zero(),this.maximumWorld=M.Zero(),this.minimum=M.Zero(),this.maximum=M.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,a=t.x,o=t.y,h=t.z,l=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(a,o,h),l[0].copyFromFloats(s,r,n),l[1].copyFromFloats(a,o,h),l[2].copyFromFloats(a,r,n),l[3].copyFromFloats(s,o,n),l[4].copyFromFloats(s,r,h),l[5].copyFromFloats(a,o,n),l[6].copyFromFloats(s,o,h),l[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||y.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Qt._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),a=this.center.subtractToRef(n,t[1]),o=this.center.addToRef(n,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const a=r[s];M.TransformCoordinatesToRef(n[s],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}M.FromArrayToRef(e.m,0,s[0]),M.FromArrayToRef(e.m,4,s[1]),M.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return Qt.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Qt.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,h=i.y,l=i.z,c=e.x,d=e.y,u=e.z,f=-a;return!(o-cc-s||h-dd-r||l-uu-n)}intersectsSphere(e){return Qt.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,a=i.z,o=s.x,h=s.y,l=s.z,c=e.x,d=e.y,u=e.z,f=t.x,_=t.y,p=t.z;return!(of||h_||lp)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=Qt._TmpVector3[0];return M.ClampToRef(i,e,t,r),M.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}Qt._TmpVector3=o.BuildArray(3,M.Zero);class $t{constructor(e,t,i){this.center=M.Zero(),this.centerWorld=M.Zero(),this.minimum=M.Zero(),this.maximum=M.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=M.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||y.IdentityReadOnly)}scale(e){const t=this.radius*e,i=$t._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{M.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=$t._TmpVector3[0];M.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=M.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=M.Dot(t.centerWorld,e),r=Math.abs(M.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(M.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(M.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},ii=(e,t,i)=>(ti(e,t,Jt),ti(e,i,ei),!(Jt.min>ei.max||ei.min>Jt.max));class si{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Qt(e,t,i),this.boundingSphere=new $t(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=si._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=si._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=M.Minimize(this.minimum,e),i=M.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=R.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=R.Vector3[0];return M.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),M.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!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,si._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(!$t.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!Qt.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(ii(i.directions[0],i,s)&&ii(i.directions[1],i,s)&&ii(i.directions[2],i,s)&&ii(s.directions[0],i,s)&&ii(s.directions[1],i,s)&&ii(s.directions[2],i,s)&&ii(M.Cross(i.directions[0],s.directions[0]),i,s)&&ii(M.Cross(i.directions[0],s.directions[1]),i,s)&&ii(M.Cross(i.directions[0],s.directions[2]),i,s)&&ii(M.Cross(i.directions[1],s.directions[0]),i,s)&&ii(M.Cross(i.directions[1],s.directions[1]),i,s)&&ii(M.Cross(i.directions[1],s.directions[2]),i,s)&&ii(M.Cross(i.directions[2],s.directions[0]),i,s)&&ii(M.Cross(i.directions[2],s.directions[1]),i,s)&&ii(M.Cross(i.directions[2],s.directions[2]),i,s))}}si._TmpVector3=o.BuildArray(2,M.Zero);class ri{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new et(0,0,0,0));return ri.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){ri.GetNearPlaneToRef(e,t[0]),ri.GetFarPlaneToRef(e,t[1]),ri.GetLeftPlaneToRef(e,t[2]),ri.GetRightPlaneToRef(e,t[3]),ri.GetTopPlaneToRef(e,t[4]),ri.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class ni extends ce{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===ni.PERSPECTIVE_CAMERA)this.fovMode===ni.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}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=M.Zero(),this._upVector=M.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=ni.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new ft(0,0,1,1),this.layerMask=268435455,this.fovMode=ni.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ni.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new se.cP,this.onProjectionMatrixChangedObservable=new se.cP,this.onAfterCheckInputsObservable=new se.cP,this.onRestoreStateObservable=new se.cP,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new y,this._postProcesses=new Array,this._activeMeshes=new nt(256),this._globalPosition=M.Zero(),this._computedViewMatrix=y.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=y.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=S.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(k.V.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?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);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return y.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){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===ni.PERSPECTIVE_CAMERA){let e;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),e=i.useRightHandedSystem?y.PerspectiveFovRHToRef:y.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ni.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?y.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,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):y.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?y.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,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):y.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,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=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.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){return(this.radius||(this.target?M.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?ri.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ri.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,re.n)("Ray")}getForwardRayToRef(e,t=100,i,s){throw(0,re.n)("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 e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==ni.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.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 e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Xe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ni.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return y.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,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Xe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eni._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ni.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=he.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=M.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(M.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(M.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw(0,re.n)("UniversalCamera")},ni.PERSPECTIVE_CAMERA=0,ni.ORTHOGRAPHIC_CAMERA=1,ni.FOVMODE_VERTICAL_FIXED=0,ni.FOVMODE_HORIZONTAL_FIXED=1,ni.RIG_MODE_NONE=0,ni.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,ni.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,ni.RIG_MODE_STEREOSCOPIC_INTERLACED=14,ni.RIG_MODE_VR=20,ni.RIG_MODE_CUSTOM=22,ni.ForceAttachControlToAlwaysPreventDefault=!1,z([J("position")],ni.prototype,"_position",void 0),z([J("upVector")],ni.prototype,"_upVector",void 0),z([q()],ni.prototype,"orthoLeft",null),z([q()],ni.prototype,"orthoRight",null),z([q()],ni.prototype,"orthoBottom",null),z([q()],ni.prototype,"orthoTop",null),z([q()],ni.prototype,"fov",void 0),z([q()],ni.prototype,"projectionPlaneTilt",void 0),z([q()],ni.prototype,"minZ",void 0),z([q()],ni.prototype,"maxZ",void 0),z([q()],ni.prototype,"inertia",void 0),z([q()],ni.prototype,"mode",null),z([q()],ni.prototype,"layerMask",void 0),z([q()],ni.prototype,"fovMode",void 0),z([q()],ni.prototype,"cameraRigMode",void 0),z([q()],ni.prototype,"interaxialDistance",void 0),z([q()],ni.prototype,"isStereoscopicSideBySide",void 0);gt.l.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";gt.l.IncludesShadersStore.instancesDeclaration="#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#ifdef INSTANCESCOLOR\nattribute vec4 instanceColor;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;\n#ifdef THIN_INSTANCES\nuniform mat4 previousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform mat4 previousWorld;\n#endif\n#endif\n";gt.l.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";gt.l.IncludesShadersStore.pointCloudVertex="#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n";gt.l.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class ai{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=st.TRILINEAR_SAMPLINGMODE,n=!1,a){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new N(1,1,1,1):this.clearColor=new N(n?1e8:1,0,0,1),ai._SceneComponentInitialization(this._scene);const o=e.getEngine();this._camera=i,r!==st.NEAREST_SAMPLINGMODE&&(1!==t||o._caps.textureFloatLinearFiltering||(r=st.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(r=st.NEAREST_SAMPLINGMODE));const h=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new St(a??"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,h),this._depthMap.wrapU=st.CLAMP_ADDRESSMODE,this._depthMap.wrapV=st.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{o._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{o._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const a=i._getWorldMatrixDeterminant()<0;let o=t.overrideMaterialSideOrientation??n.sideOrientation;a&&(o=0===o?1:0);const h=0===o;r.setState(n.backFaceCulling,0,!1,h,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const l=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(l.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==l.visibleInstances[e._id]&&void 0!==l.visibleInstances[e._id]||t.hasThinInstances),d=this._camera||s.activeCamera;if(this.isReady(e,c)&&d){e._renderId=s.getRenderId();const a=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let o=e._getDrawWrapper();!o&&a&&(o=a._getDrawWrapper());const h=d.mode===ni.ORTHOGRAPHIC_CAMERA;if(!o)return;const u=o.effect;let f,_;if(r.enableEffect(o),c||t._bind(e,u,n.fillMode),a?a.bindForSubMesh(i.getWorldMatrix(),i,e):(u.setMatrix("viewProjection",s.getTransformMatrix()),u.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&u.setMatrix("view",s.getViewMatrix())),h?(f=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(f=r.useReverseDepthBuffer&&r.isNDCHalfZRange?d.minZ:r.isNDCHalfZRange?0:d.minZ,_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:d.maxZ),u.setFloat2("depthValues",f,f+_),!a){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(u.setTexture("diffuseSampler",e),u.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;u.setTexture("boneSampler",i),u.setFloat("boneTextureWidth",4*(e.bones.length+1))}else u.setMatrices("mBones",e.getTransformMatrices(t))}Ot(u,n,s),Gt(t,u),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(u),n.pointsCloud&&u.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,u,n.fillMode,l,c,((e,t)=>u.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(h.push(G.MatricesIndicesExtraKind),h.push(G.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),o.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&o.push("#define BONETEXTURE")}else o.push("#define NUM_BONE_INFLUENCERS 0");const l=s.morphTargetManager;let c=0;l&&(c=l.numMaxInfluencers||l.numInfluencers,c>0&&(o.push("#define MORPHTARGETS"),o.push("#define NUM_MORPH_INFLUENCERS "+c),l.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),Ut(h,s,c))),a.pointsCloud&&o.push("#define POINTSIZE"),t&&(o.push("#define INSTANCES"),Vt(h),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&o.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&o.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&o.push("#define PACKED"),Dt(a,r,o);const d=e._getDrawWrapper(void 0,!0),u=d.defines,f=o.join("\n");if(u!==f){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Pt(e),d.setEffect(i.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),f)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}ai._SceneComponentInitialization=e=>{throw(0,re.n)("DepthRendererSceneComponent")};gt.l.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class oi{constructor(e){this.onAfterReductionPerformed=new se.cP,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new rt(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new It("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let a=this._sourceTexture.getRenderWidth(),o=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(a,o),this._reductionSteps.push(n);let h=1;for(;a>1||o>1;){a=Math.max(Math.round(a/2),1),o=Math.max(Math.round(o/2),1);const e=new It("Reduction phase "+h,"minmaxRedux",["texSize"],null,{width:a,height:o},null,1,r.getEngine(),!1,"#define "+(1==a&&1==o?"LAST":1==a||1==o?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(a,o),this._reductionSteps.push(e),h++,1==a&&1==o){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(a,o,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return _i.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,a=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,o=a-n,h=a/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Zt.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Zt.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Zt.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===Zt.FILTER_PCSS){for(let e=0;enew _i(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}_i._FrustumCornersNDCSpace=[new M(-1,1,-1),new M(1,1,-1),new M(1,-1,-1),new M(-1,-1,-1),new M(-1,1,1),new M(1,1,1),new M(1,-1,1),new M(-1,-1,1)],_i.CLASSNAME="CascadedShadowGenerator",_i.DEFAULT_CASCADES_COUNT=4,_i.MIN_CASCADES_COUNT=2,_i.MAX_CASCADES_COUNT=4,_i._SceneComponentInitialization=e=>{throw(0,re.n)("ShadowGeneratorSceneComponent")};class pi{}pi.NAME_EFFECTLAYER="EffectLayer",pi.NAME_LAYER="Layer",pi.NAME_LENSFLARESYSTEM="LensFlareSystem",pi.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",pi.NAME_PARTICLESYSTEM="ParticleSystem",pi.NAME_GAMEPAD="Gamepad",pi.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",pi.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",pi.NAME_PREPASSRENDERER="PrePassRenderer",pi.NAME_DEPTHRENDERER="DepthRenderer",pi.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",pi.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",pi.NAME_SPRITE="Sprite",pi.NAME_SUBSURFACE="SubSurface",pi.NAME_OUTLINERENDERER="Outline",pi.NAME_PROCEDURALTEXTURE="ProceduralTexture",pi.NAME_SHADOWGENERATOR="ShadowGenerator",pi.NAME_OCTREE="Octree",pi.NAME_PHYSICSENGINE="PhysicsEngine",pi.NAME_AUDIO="Audio",pi.NAME_FLUIDRENDERER="FluidRenderer",pi.STEP_ISREADYFORMESH_EFFECTLAYER=0,pi.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,pi.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,pi.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,pi.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,pi.STEP_BEFORECAMERADRAW_PREPASS=0,pi.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,pi.STEP_BEFORECAMERADRAW_LAYER=2,pi.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,pi.STEP_BEFORERENDERTARGETDRAW_LAYER=1,pi.STEP_BEFORERENDERINGMESH_PREPASS=0,pi.STEP_BEFORERENDERINGMESH_OUTLINE=1,pi.STEP_AFTERRENDERINGMESH_PREPASS=0,pi.STEP_AFTERRENDERINGMESH_OUTLINE=1,pi.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,pi.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,pi.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,pi.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,pi.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,pi.STEP_BEFORECLEAR_PREPASS=1,pi.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,pi.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,pi.STEP_AFTERRENDERTARGETDRAW_LAYER=1,pi.STEP_AFTERCAMERADRAW_PREPASS=0,pi.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,pi.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,pi.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,pi.STEP_AFTERCAMERADRAW_LAYER=4,pi.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,pi.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,pi.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,pi.STEP_AFTERRENDER_AUDIO=0,pi.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,pi.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,pi.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,pi.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,pi.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,pi.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,pi.STEP_POINTERMOVE_SPRITE=0,pi.STEP_POINTERDOWN_SPRITE=0,pi.STEP_POINTERUP_SPRITE=0;class gi extends Array{constructor(e){super(...e)}static Create(){return Object.create(gi.prototype)}registerStep(e,t,i){let s=0,r=Number.MAX_VALUE;for(;se=e.concat(t.bones))),e}}mi._BabylonFileParsers={},mi._IndividualBabylonFileParsers={},d("BABYLON.AbstractScene",mi),mi.AddParser(pi.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;it.length)return void k.V.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,a=!1,o=!1;switch(s.image_type){case 9:n=!0;case 1:a=!0;break;case 10:n=!0;case 2:break;case 11:n=!0;case 3:o=!0}const h=s.pixel_size>>3,l=s.width*s.height*h;let c,d,u,f,_,p,g;if(a&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(l);let a=0;const o=new Uint8Array(h);for(;i>4){default:case 2:d=0,f=1,g=s.width,u=0,_=1,p=s.height;break;case 0:d=0,f=1,g=s.width,u=s.height-1,_=-1,p=-1;break;case 3:d=s.width-1,f=-1,g=-1,u=0,_=1,p=s.height;break;case 1:d=s.width-1,f=-1,g=-1,u=s.height-1,_=-1,p=-1}const m="_getImageData"+(o?"Grey":"")+s.pixel_size+"bits",T=vi[m](s,c,r,u,_,p,d,f,g);e.getEngine()._uploadDataToTextureDirectly(e,T)}Zt._SceneComponentInitialization=e=>{let t=e._getComponent(pi.NAME_SHADOWGENERATOR);t||(t=new Ti(e),e._addComponent(t))};const vi={GetTGAHeader:xi,UploadContent:Ei,_getImageData8bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=t,d=e.width,u=e.height;let f,_,p,g=0;const m=new Uint8Array(d*u*4);for(p=s;p!==n;p+=r)for(_=a;_!==h;_+=o,g++)f=l[g],m[4*(_+d*p)+3]=255,m[4*(_+d*p)+2]=c[3*f+0],m[4*(_+d*p)+1]=c[3*f+1],m[4*(_+d*p)+0]=c[3*f+2];return m},_getImageData16bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_,p=0;const g=new Uint8Array(c*d*4);for(_=s;_!==n;_+=r)for(f=a;f!==h;f+=o,p+=2){u=l[p+0]+(l[p+1]<<8);const e=255*((31744&u)>>10)/31|0,t=255*((992&u)>>5)/31|0,i=255*(31&u)/31|0;g[4*(f+c*_)+0]=e,g[4*(f+c*_)+1]=t,g[4*(f+c*_)+2]=i,g[4*(f+c*_)+3]=32768&u?0:255}return g},_getImageData24bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_=0;const p=new Uint8Array(c*d*4);for(f=s;f!==n;f+=r)for(u=a;u!==h;u+=o,_+=3)p[4*(u+c*f)+3]=255,p[4*(u+c*f)+2]=l[_+0],p[4*(u+c*f)+1]=l[_+1],p[4*(u+c*f)+0]=l[_+2];return p},_getImageData32bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_=0;const p=new Uint8Array(c*d*4);for(f=s;f!==n;f+=r)for(u=a;u!==h;u+=o,_+=4)p[4*(u+c*f)+2]=l[_+0],p[4*(u+c*f)+1]=l[_+1],p[4*(u+c*f)+0]=l[_+2],p[4*(u+c*f)+3]=l[_+3];return p},_getImageDataGrey8bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_,p=0;const g=new Uint8Array(c*d*4);for(_=s;_!==n;_+=r)for(f=a;f!==h;f+=o,p++)u=l[p],g[4*(f+c*_)+0]=u,g[4*(f+c*_)+1]=u,g[4*(f+c*_)+2]=u,g[4*(f+c*_)+3]=255;return g},_getImageDataGrey16bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_=0;const p=new Uint8Array(c*d*4);for(f=s;f!==n;f+=r)for(u=a;u!==h;u+=o,_+=2)p[4*(u+c*f)+0]=l[_+0],p[4*(u+c*f)+1]=l[_+0],p[4*(u+c*f)+2]=l[_+0],p[4*(u+c*f)+3]=l[_+1];return p}};var Ai=i(67);Ai.N._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=xi(s);i(r.width,r.height,t.generateMipMaps,!1,(()=>{Ei(t,s)}))}});gt.l.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying float vFragmentDepth;\n#endif\n";gt.l.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n";gt.l.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";gt.l.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n";gt.l.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n";class Mi{}Mi.AUTOSAMPLERSUFFIX="Sampler",Mi.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",Mi.ALPHA_DISABLE=0,Mi.ALPHA_ADD=1,Mi.ALPHA_COMBINE=2,Mi.ALPHA_SUBTRACT=3,Mi.ALPHA_MULTIPLY=4,Mi.ALPHA_MAXIMIZED=5,Mi.ALPHA_ONEONE=6,Mi.ALPHA_PREMULTIPLIED=7,Mi.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Mi.ALPHA_INTERPOLATE=9,Mi.ALPHA_SCREENMODE=10,Mi.ALPHA_ONEONE_ONEONE=11,Mi.ALPHA_ALPHATOCOLOR=12,Mi.ALPHA_REVERSEONEMINUS=13,Mi.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Mi.ALPHA_ONEONE_ONEZERO=15,Mi.ALPHA_EXCLUSION=16,Mi.ALPHA_LAYER_ACCUMULATE=17,Mi.ALPHA_EQUATION_ADD=0,Mi.ALPHA_EQUATION_SUBSTRACT=1,Mi.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Mi.ALPHA_EQUATION_MAX=3,Mi.ALPHA_EQUATION_MIN=4,Mi.ALPHA_EQUATION_DARKEN=5,Mi.DELAYLOADSTATE_NONE=0,Mi.DELAYLOADSTATE_LOADED=1,Mi.DELAYLOADSTATE_LOADING=2,Mi.DELAYLOADSTATE_NOTLOADED=4,Mi.NEVER=512,Mi.ALWAYS=519,Mi.LESS=513,Mi.EQUAL=514,Mi.LEQUAL=515,Mi.GREATER=516,Mi.GEQUAL=518,Mi.NOTEQUAL=517,Mi.KEEP=7680,Mi.ZERO=0,Mi.REPLACE=7681,Mi.INCR=7682,Mi.DECR=7683,Mi.INVERT=5386,Mi.INCR_WRAP=34055,Mi.DECR_WRAP=34056,Mi.TEXTURE_CLAMP_ADDRESSMODE=0,Mi.TEXTURE_WRAP_ADDRESSMODE=1,Mi.TEXTURE_MIRROR_ADDRESSMODE=2,Mi.TEXTURE_CREATIONFLAG_STORAGE=1,Mi.TEXTUREFORMAT_ALPHA=0,Mi.TEXTUREFORMAT_LUMINANCE=1,Mi.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Mi.TEXTUREFORMAT_RGB=4,Mi.TEXTUREFORMAT_RGBA=5,Mi.TEXTUREFORMAT_RED=6,Mi.TEXTUREFORMAT_R=6,Mi.TEXTUREFORMAT_RG=7,Mi.TEXTUREFORMAT_RED_INTEGER=8,Mi.TEXTUREFORMAT_R_INTEGER=8,Mi.TEXTUREFORMAT_RG_INTEGER=9,Mi.TEXTUREFORMAT_RGB_INTEGER=10,Mi.TEXTUREFORMAT_RGBA_INTEGER=11,Mi.TEXTUREFORMAT_BGRA=12,Mi.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Mi.TEXTUREFORMAT_DEPTH32_FLOAT=14,Mi.TEXTUREFORMAT_DEPTH16=15,Mi.TEXTUREFORMAT_DEPTH24=16,Mi.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Mi.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Mi.TEXTUREFORMAT_STENCIL8=19,Mi.TEXTUREFORMAT_UNDEFINED=4294967295,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Mi.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Mi.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Mi.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Mi.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Mi.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Mi.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Mi.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Mi.TEXTURETYPE_UNSIGNED_BYTE=0,Mi.TEXTURETYPE_UNSIGNED_INT=0,Mi.TEXTURETYPE_FLOAT=1,Mi.TEXTURETYPE_HALF_FLOAT=2,Mi.TEXTURETYPE_BYTE=3,Mi.TEXTURETYPE_SHORT=4,Mi.TEXTURETYPE_UNSIGNED_SHORT=5,Mi.TEXTURETYPE_INT=6,Mi.TEXTURETYPE_UNSIGNED_INTEGER=7,Mi.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Mi.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Mi.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Mi.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Mi.TEXTURETYPE_UNSIGNED_INT_24_8=12,Mi.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Mi.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Mi.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Mi.TEXTURETYPE_UNDEFINED=16,Mi.TEXTURE_2D=3553,Mi.TEXTURE_2D_ARRAY=35866,Mi.TEXTURE_CUBE_MAP=34067,Mi.TEXTURE_CUBE_MAP_ARRAY=3735928559,Mi.TEXTURE_3D=32879,Mi.TEXTURE_NEAREST_SAMPLINGMODE=1,Mi.TEXTURE_NEAREST_NEAREST=1,Mi.TEXTURE_BILINEAR_SAMPLINGMODE=2,Mi.TEXTURE_LINEAR_LINEAR=2,Mi.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Mi.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Mi.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Mi.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Mi.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Mi.TEXTURE_NEAREST_LINEAR=7,Mi.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Mi.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Mi.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Mi.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Mi.TEXTURE_LINEAR_NEAREST=12,Mi.TEXTURE_EXPLICIT_MODE=0,Mi.TEXTURE_SPHERICAL_MODE=1,Mi.TEXTURE_PLANAR_MODE=2,Mi.TEXTURE_CUBIC_MODE=3,Mi.TEXTURE_PROJECTION_MODE=4,Mi.TEXTURE_SKYBOX_MODE=5,Mi.TEXTURE_INVCUBIC_MODE=6,Mi.TEXTURE_EQUIRECTANGULAR_MODE=7,Mi.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Mi.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Mi.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Mi.TEXTURE_FILTERING_QUALITY_HIGH=64,Mi.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Mi.TEXTURE_FILTERING_QUALITY_LOW=8,Mi.SCALEMODE_FLOOR=1,Mi.SCALEMODE_NEAREST=2,Mi.SCALEMODE_CEILING=3,Mi.MATERIAL_TextureDirtyFlag=1,Mi.MATERIAL_LightDirtyFlag=2,Mi.MATERIAL_FresnelDirtyFlag=4,Mi.MATERIAL_AttributesDirtyFlag=8,Mi.MATERIAL_MiscDirtyFlag=16,Mi.MATERIAL_PrePassDirtyFlag=32,Mi.MATERIAL_AllDirtyFlag=63,Mi.MATERIAL_TriangleFillMode=0,Mi.MATERIAL_WireFrameFillMode=1,Mi.MATERIAL_PointFillMode=2,Mi.MATERIAL_PointListDrawMode=3,Mi.MATERIAL_LineListDrawMode=4,Mi.MATERIAL_LineLoopDrawMode=5,Mi.MATERIAL_LineStripDrawMode=6,Mi.MATERIAL_TriangleStripDrawMode=7,Mi.MATERIAL_TriangleFanDrawMode=8,Mi.MATERIAL_ClockWiseSideOrientation=0,Mi.MATERIAL_CounterClockWiseSideOrientation=1,Mi.ACTION_NothingTrigger=0,Mi.ACTION_OnPickTrigger=1,Mi.ACTION_OnLeftPickTrigger=2,Mi.ACTION_OnRightPickTrigger=3,Mi.ACTION_OnCenterPickTrigger=4,Mi.ACTION_OnPickDownTrigger=5,Mi.ACTION_OnDoublePickTrigger=6,Mi.ACTION_OnPickUpTrigger=7,Mi.ACTION_OnPickOutTrigger=16,Mi.ACTION_OnLongPressTrigger=8,Mi.ACTION_OnPointerOverTrigger=9,Mi.ACTION_OnPointerOutTrigger=10,Mi.ACTION_OnEveryFrameTrigger=11,Mi.ACTION_OnIntersectionEnterTrigger=12,Mi.ACTION_OnIntersectionExitTrigger=13,Mi.ACTION_OnKeyDownTrigger=14,Mi.ACTION_OnKeyUpTrigger=15,Mi.PARTICLES_BILLBOARDMODE_Y=2,Mi.PARTICLES_BILLBOARDMODE_ALL=7,Mi.PARTICLES_BILLBOARDMODE_STRETCHED=8,Mi.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Mi.MESHES_CULLINGSTRATEGY_STANDARD=0,Mi.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Mi.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Mi.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Mi.SCENELOADER_NO_LOGGING=0,Mi.SCENELOADER_MINIMAL_LOGGING=1,Mi.SCENELOADER_SUMMARY_LOGGING=2,Mi.SCENELOADER_DETAILED_LOGGING=3,Mi.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Mi.PREPASS_POSITION_TEXTURE_TYPE=1,Mi.PREPASS_VELOCITY_TEXTURE_TYPE=2,Mi.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Mi.PREPASS_COLOR_TEXTURE_TYPE=4,Mi.PREPASS_DEPTH_TEXTURE_TYPE=5,Mi.PREPASS_NORMAL_TEXTURE_TYPE=6,Mi.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Mi.BUFFER_CREATIONFLAG_READ=1,Mi.BUFFER_CREATIONFLAG_WRITE=2,Mi.BUFFER_CREATIONFLAG_READWRITE=3,Mi.BUFFER_CREATIONFLAG_UNIFORM=4,Mi.BUFFER_CREATIONFLAG_VERTEX=8,Mi.BUFFER_CREATIONFLAG_INDEX=16,Mi.BUFFER_CREATIONFLAG_STORAGE=32,Mi.BUFFER_CREATIONFLAG_INDIRECT=64,Mi.RENDERPASS_MAIN=0,Mi.INPUT_ALT_KEY=18,Mi.INPUT_CTRL_KEY=17,Mi.INPUT_META_KEY1=91,Mi.INPUT_META_KEY2=92,Mi.INPUT_META_KEY3=93,Mi.INPUT_SHIFT_KEY=16,Mi.SNAPSHOTRENDERING_STANDARD=0,Mi.SNAPSHOTRENDERING_FAST=1,Mi.PERSPECTIVE_CAMERA=0,Mi.ORTHOGRAPHIC_CAMERA=1,Mi.FOVMODE_VERTICAL_FIXED=0,Mi.FOVMODE_HORIZONTAL_FIXED=1,Mi.RIG_MODE_NONE=0,Mi.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Mi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Mi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Mi.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Mi.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Mi.RIG_MODE_VR=20,Mi.RIG_MODE_CUSTOM=22,Mi.MAX_SUPPORTED_UV_SETS=6,Mi.GL_ALPHA_EQUATION_ADD=32774,Mi.GL_ALPHA_EQUATION_MIN=32775,Mi.GL_ALPHA_EQUATION_MAX=32776,Mi.GL_ALPHA_EQUATION_SUBTRACT=32778,Mi.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Mi.GL_ALPHA_FUNCTION_SRC=768,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Mi.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Mi.GL_ALPHA_FUNCTION_DST_ALPHA=772,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Mi.GL_ALPHA_FUNCTION_DST_COLOR=774,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Mi.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Mi.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Mi.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Mi.SnippetUrl="https://snippet.babylonjs.com",Mi.FOGMODE_NONE=0,Mi.FOGMODE_EXP=1,Mi.FOGMODE_EXP2=2,Mi.FOGMODE_LINEAR=3,Mi.BYTE=5120,Mi.UNSIGNED_BYTE=5121,Mi.SHORT=5122,Mi.UNSIGNED_SHORT=5123,Mi.INT=5124,Mi.UNSIGNED_INT=5125,Mi.FLOAT=5126,Mi.PositionKind="position",Mi.NormalKind="normal",Mi.TangentKind="tangent",Mi.UVKind="uv",Mi.UV2Kind="uv2",Mi.UV3Kind="uv3",Mi.UV4Kind="uv4",Mi.UV5Kind="uv5",Mi.UV6Kind="uv6",Mi.ColorKind="color",Mi.ColorInstanceKind="instanceColor",Mi.MatricesIndicesKind="matricesIndices",Mi.MatricesWeightsKind="matricesWeights",Mi.MatricesIndicesExtraKind="matricesIndicesExtra",Mi.MatricesWeightsExtraKind="matricesWeightsExtra";class bi{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach(((e,t)=>this.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function Si(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class yi{constructor(){this._dirty=!0,this._tempColor=new N(0,0,0,0),this._globalCurve=new N(0,0,0,0),this._highlightsCurve=new N(0,0,0,0),this._midtonesCurve=new N(0,0,0,0),this._shadowsCurve=new N(0,0,0,0),this._positiveCurve=new N(0,0,0,0),this._negativeCurve=new N(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",r="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(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=yi._Clamp(e,0,360),t=yi._Clamp(t,-100,100),i=yi._Clamp(i,-100,100),s=yi._Clamp(s,-100,100),t=yi._ApplyColorGradingSliderNonlinear(t),t*=.5,s=yi._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),yi._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.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 r=yi._Clamp(e,0,360);const n=yi._Clamp(t/100,0,1),a=yi._Clamp(i/100,0,1);if(0===n)s.r=a,s.g=a,s.b=a;else{r/=60;const e=Math.floor(r),t=r-e,i=a*(1-n),o=a*(1-n*t),h=a*(1-n*(1-t));switch(e){case 0:s.r=a,s.g=h,s.b=i;break;case 1:s.r=o,s.g=a,s.b=i;break;case 2:s.r=i,s.g=a,s.b=h;break;case 3:s.r=i,s.g=o,s.b=a;break;case 4:s.r=h,s.g=i,s.b=a;break;default:s.r=a,s.g=i,s.b=o}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return he.Clone((()=>new yi),this)}serialize(){return he.Serialize(this)}static Parse(e){return he.Parse((()=>new yi),e,null,null)}}yi.PrepareUniforms=Si,z([q()],yi.prototype,"_globalHue",void 0),z([q()],yi.prototype,"_globalDensity",void 0),z([q()],yi.prototype,"_globalSaturation",void 0),z([q()],yi.prototype,"_globalExposure",void 0),z([q()],yi.prototype,"_highlightsHue",void 0),z([q()],yi.prototype,"_highlightsDensity",void 0),z([q()],yi.prototype,"_highlightsSaturation",void 0),z([q()],yi.prototype,"_highlightsExposure",void 0),z([q()],yi.prototype,"_midtonesHue",void 0),z([q()],yi.prototype,"_midtonesDensity",void 0),z([q()],yi.prototype,"_midtonesSaturation",void 0),z([q()],yi.prototype,"_midtonesExposure",void 0),he._ColorCurvesParser=yi.Parse;class Ii{constructor(){this.colorCurves=new yi,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Ii.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new N(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Ii.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new se.cP}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)return 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,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Ii._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case Ii.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Ii.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,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&&yi.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),a=n*r;const o=Math.sqrt(a*n);a=(0,We.zF)(a,o,this.vignetteStretch),n=(0,We.zF)(n,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return he.Clone((()=>new Ii),this)}serialize(){return he.Serialize(this)}static Parse(e){const t=he.Parse((()=>new Ii),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}var Ri,Ci,Pi,Di,Oi,Fi,wi,Li;Ii.TONEMAPPING_STANDARD=0,Ii.TONEMAPPING_ACES=1,Ii.TONEMAPPING_KHR_PBR_NEUTRAL=2,Ii.PrepareUniforms=function(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Si(e),t.DITHER&&e.push("ditherIntensity")},Ii.PrepareSamplers=function(e,t){t.COLORGRADING&&e.push("txColorTransform")},Ii._VIGNETTEMODE_MULTIPLY=0,Ii._VIGNETTEMODE_OPAQUE=1,z([K(7,undefined)],Ii.prototype,"colorCurves",void 0),z([q()],Ii.prototype,"_colorCurvesEnabled",void 0),z([j("colorGradingTexture")],Ii.prototype,"_colorGradingTexture",void 0),z([q()],Ii.prototype,"_colorGradingEnabled",void 0),z([q()],Ii.prototype,"_colorGradingWithGreenDepth",void 0),z([q()],Ii.prototype,"_colorGradingBGR",void 0),z([q()],Ii.prototype,"_exposure",void 0),z([q()],Ii.prototype,"_toneMappingEnabled",void 0),z([q()],Ii.prototype,"_toneMappingType",void 0),z([q()],Ii.prototype,"_contrast",void 0),z([q()],Ii.prototype,"vignetteStretch",void 0),z([q()],Ii.prototype,"vignetteCenterX",void 0),z([q()],Ii.prototype,"vignetteCenterY",void 0),z([q()],Ii.prototype,"vignetteWeight",void 0),z([te()],Ii.prototype,"vignetteColor",void 0),z([q()],Ii.prototype,"vignetteCameraFov",void 0),z([q()],Ii.prototype,"_vignetteBlendMode",void 0),z([q()],Ii.prototype,"_vignetteEnabled",void 0),z([q()],Ii.prototype,"_ditheringEnabled",void 0),z([q()],Ii.prototype,"_ditheringIntensity",void 0),z([q()],Ii.prototype,"_skipFinalColorClamp",void 0),z([q()],Ii.prototype,"_applyByPostProcess",void 0),z([q()],Ii.prototype,"_isEnabled",void 0),he._ImageProcessingConfigurationParser=Ii.Parse,d("BABYLON.ImageProcessingConfiguration",Ii);class Ni{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(G.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=R.Vector3[0],n=R.Vector3[1],a=R.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(G.NormalKind);let t=s?M.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=s?M.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=s?M.FromArrayToRef(e,3*s[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),o=o.scale(this.bv),h=h.scale(1-this.bu-this.bv),i=new M(t.x+o.x+h.x,t.y+o.y+h.y,t.z+o.z+h.z)}else{const e=this.pickedMesh.getVerticesData(G.PositionKind),t=s?M.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=s?M.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=s?M.FromArrayToRef(e,3*s[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),l=t.subtract(o),c=h.subtract(o);i=M.Cross(l,c)}const o=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(R.Matrix[0].copyFrom(i),i=R.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(R.Matrix[1]),i=R.Matrix[1]),M.TransformNormalToRef(t,i,t)};if(e&&o(this.pickedMesh,i),this.ray){const t=R.Vector3[0].copyFrom(i);e||o(this.pickedMesh,t),M.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=G.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=A.FromArray(i,2*t[3*this.faceId]),r=A.FromArray(i,2*t[3*this.faceId+1]),n=A.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new A(s.x+r.x+n.x,s.y+r.y+n.y)}}class Bi{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new Bi(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Bi(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Bi(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Bi(e,t.x,t.y,null,i,s)}}class Ui{}Ui.POINTERDOWN=1,Ui.POINTERUP=2,Ui.POINTERMOVE=4,Ui.POINTERWHEEL=8,Ui.POINTERPICK=16,Ui.POINTERTAP=32,Ui.POINTERDOUBLETAP=64;class ki{constructor(e,t){this.type=e,this.event=t}}class Vi extends ki{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new A(i,s)}}class Gi extends ki{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,s=null){super(e,t),this._pickInfo=i,this._inputManager=s}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class zi{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in zi.Triggers)if(Object.prototype.hasOwnProperty.call(zi.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in zi.Triggers)if(Object.prototype.hasOwnProperty.call(zi.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in zi.Triggers)if(Object.prototype.hasOwnProperty.call(zi.Triggers,t)&&parseInt(t)===e)return!0;return!1}}zi.Triggers={};class Wi{}Wi.KEYDOWN=1,Wi.KEYUP=2;class Xi{constructor(e,t){this.type=e,this.event=t}}class Hi extends Xi{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}}!function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(Ri||(Ri={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(Ci||(Ci={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(Pi||(Pi={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Di||(Di={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Oi||(Oi={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(Fi||(Fi={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(wi||(wi={})),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(Li||(Li={}));class Ki{}Ki.DOM_DELTA_PIXEL=0,Ki.DOM_DELTA_LINE=1,Ki.DOM_DELTA_PAGE=2;class Yi{static CreateDeviceEvent(e,t,i,s,r,n,a){switch(e){case Ri.Keyboard:return this._CreateKeyboardEvent(i,s,r,n);case Ri.Mouse:if(i===Ci.MouseWheelX||i===Ci.MouseWheelY||i===Ci.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,r,n);case Ri.Touch:return this._CreatePointerEvent(e,t,i,s,r,n,a);default:throw`Unable to generate event for device ${Ri[e]}`}}static _CreatePointerEvent(e,t,i,s,r,n,a){const o=this._CreateMouseEvent(e,t,i,s,r,n);e===Ri.Mouse?(o.deviceType=Ri.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=Ri.Touch,o.pointerId=a??t,o.pointerType="touch");let h=0;return h+=r.pollInput(e,t,Ci.LeftClick),h+=2*r.pollInput(e,t,Ci.RightClick),h+=4*r.pollInput(e,t,Ci.MiddleClick),o.buttons=h,i===Ci.Move?o.type="pointermove":i>=Ci.LeftClick&&i<=Ci.RightClick&&(o.type=1===s?"pointerdown":"pointerup",o.button=i-2),o}static _CreateWheelEvent(e,t,i,s,r,n){const a=this._CreateMouseEvent(e,t,i,s,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=Ki.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case Ci.MouseWheelX:a.deltaX=s;break;case Ci.MouseWheelY:a.deltaY=s;break;case Ci.MouseWheelZ:a.deltaZ=s}return a}static _CreateMouseEvent(e,t,i,s,r,n){const a=this._CreateEvent(n),o=r.pollInput(e,t,Ci.Horizontal),h=r.pollInput(e,t,Ci.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,Pi.DeltaHorizontal),a.movementY=r.pollInput(e,t,Pi.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=o,a.clientY=h,a.x=o,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=Ri.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(Ri.Keyboard),s=i&&1===t.pollInput(Ri.Keyboard,0,18),r=i&&1===t.pollInput(Ri.Keyboard,0,17),n=i&&(1===t.pollInput(Ri.Keyboard,0,91)||1===t.pollInput(Ri.Keyboard,0,92)||1===t.pollInput(Ri.Keyboard,0,93)),a=i&&1===t.pollInput(Ri.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class qi{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=Yi.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Ri.Mouse||e===Ri.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const ji=Object.keys(Ci).length/2;class Zi{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Xe.IsSafari(),this._usingMacOS=(0,de.XD)()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=(0,de.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=(0,de.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Xe.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 ${Ri[e]}`;e>=Ri.DualShock&&e<=Ri.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${Ri[e]} in slot ${t}`;return i===Ci.Move&&Xe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ri.Keyboard,0,255));const t=this._inputs[Ri.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(Ri.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ri.Keyboard,0,255));const t=this._inputs[Ri.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=Yi.CreateDeviceEvent(Ri.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Ri.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Ri.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Ri.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===Ri.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ri.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void Xe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=Ci.Move,s[Ci.Horizontal]=e.clientX,s[Ci.Vertical]=e.clientY,t===Ri.Touch&&0===s[Ci.LeftClick]&&(s[Ci.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===Ri.Mouse?0:e.pointerId;if(t===Ri.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void Xe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===Ri.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[Ci.Horizontal],n=s[Ci.Vertical];if(t===Ri.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[Ci.Horizontal]=e.clientX,s[Ci.Vertical]=e.clientY,s[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),r===e.clientX&&n===e.clientY||(a.inputIndex=Ci.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===Ri.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ri.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[Ci.Horizontal],n=s[Ci.Vertical];s[Ci.Horizontal]=e.clientX,s[Ci.Vertical]=e.clientY,s[e.button+2]=0;const a=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(a.inputIndex=Ci.Move,this._onInputChanged(t,i,a)),a.inputIndex=e.button+2,t===Ri.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,a),t===Ri.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[Ri.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Ci.LeftClick;t<=Ci.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Yi.CreateDeviceEvent(Ri.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ri.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[Ri.Touch][t][Ci.LeftClick]=0;const i=Yi.CreateDeviceEvent(Ri.Touch,t,Ci.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(Ri.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Ri.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"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(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(Ri.Mouse)){const e=this._inputs[Ri.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Ci.LeftClick;t<=Ci.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Yi.CreateDeviceEvent(Ri.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ri.Mouse,0,i)}}if(this.isDeviceAvailable(Ri.Touch)){const e=this._inputs[Ri.Touch];for(let t=0;t{const t=Ri.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,ji));const i=this._inputs[t][0];if(i){i[Ci.MouseWheelX]=e.deltaX||0,i[Ci.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[Ci.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[Ci.MouseWheelX]&&(s.inputIndex=Ci.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[Ci.MouseWheelY]&&(s.inputIndex=Ci.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[Ci.MouseWheelZ]&&(s.inputIndex=Ci.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},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}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(Ri.Mouse)){const e=this._inputs[Ri.Mouse][0];e[Ci.MouseWheelX]=0,e[Ci.MouseWheelY]=0,e[Ci.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Ri.DualSense:Ri.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Ri.Xbox:-1!==e.indexOf("057e")?Ri.Switch:Ri.Generic}_getPointerType(e){let t=Ri.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Ri.Touch),t}}class Qi{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new se.cP,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class $i{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(Ri).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new Qi(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new qi(i,s,r):this._deviceInputSystem=new Zi(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Ji{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(Ri).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new $i(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new se.cP((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new se.cP,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){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Ri.Keyboard:case Ri.Mouse:this._firstDevice[e]=0;break;case Ri.Touch:case Ri.DualSense:case Ri.DualShock:case Ri.Xbox:case Ri.Switch:case Ri.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=Ci.MouseWheelX&&t.inputIndex<=Ci.MouseWheelZ?Ui.POINTERWHEEL:Ui.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(a=new Gi(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new Gi(n,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,y.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new Vi(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=Ci.Move,this._checkPrePointerObservable(e,i,Ui.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,Ui.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,Bi.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,Bi.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,Bi.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,Bi.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>ts.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,Bi.CreateNew(e.pickedMesh,t)))}),ts.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=Ui.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new Gi(r,t,e),this._setRayOnPointerInfo(e,t)):s=new Gi(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=Ci.Move;const r=new es;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,Ui.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=Ui.POINTERPICK,r=new Gi(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,Bi.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,Bi.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,Bi.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,Bi.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Gi(Ui.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,Ui.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Ui.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Ui.POINTERTAP:i.doubleClick&&(r=Ui.POINTERDOUBLETAP),r){const i=new Gi(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Ji(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>ts.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=Ui.POINTERTAP,s=new Gi(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new es;this._currentPickResult=null;let n=null,a=e.hasSpecificMask(Ui.POINTERPICK)||t.hasSpecificMask(Ui.POINTERPICK)||e.hasSpecificMask(Ui.POINTERTAP)||t.hasSpecificMask(Ui.POINTERTAP)||e.hasSpecificMask(Ui.POINTERDOUBLETAP)||t.hasSpecificMask(Ui.POINTERDOUBLETAP);!a&&zi&&(n=this._initActionManager(n,r),n&&(a=n.hasPickTriggers));let o=!1;if(a){const a=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let h=!ts.ExclusiveDoubleClickMode;if(h||(h=!e.hasSpecificMask(Ui.POINTERDOUBLETAP)&&!t.hasSpecificMask(Ui.POINTERDOUBLETAP),h&&!zi.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=!n.hasSpecificTrigger(6)))),h)(Date.now()-this._previousStartingPointerTime>ts.DoubleClickDelay||a!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),o=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,a,r,s),ts.DoubleClickDelay)};this._delayedClicks[a]=e}let l=e.hasSpecificMask(Ui.POINTERDOUBLETAP)||t.hasSpecificMask(Ui.POINTERDOUBLETAP);!l&&zi.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=n.hasSpecificTrigger(6))),l&&(a===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>ts.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>ts.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=Ci.MouseWheelX&&e.inputIndex<=Ci.MouseWheelZ?Ui.POINTERWHEEL:Ui.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new Ni,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,ts.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new Ni:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,Ui.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(Ui.POINTERTAP)&&this._checkPrePointerObservable(null,e,Ui.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Ui.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,Ui.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(zi&&zi.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=Wi.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new Hi(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Xi(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,Bi.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Wi.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new Hi(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Xi(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,Bi.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===Ri.Mouse?s.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===Ci.LeftClick||r.inputIndex===Ci.MiddleClick||r.inputIndex===Ci.RightClick||r.inputIndex===Ci.BrowserBack||r.inputIndex===Ci.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===Ci.Move?this._onPointerMove(r):r.inputIndex!==Ci.MouseWheelX&&r.inputIndex!==Ci.MouseWheelY&&r.inputIndex!==Ci.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===Ri.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===Ci.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===Ci.Move&&this._onPointerMove(r)})):s.deviceType===Ri.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,Bi.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,Bi.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]}}ts.DragMovementThreshold=10,ts.LongPressDelay=500,ts.DoubleClickDelay=300,ts.ExclusiveDoubleClickMode=!1;var is,ss=i(296);class rs{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}rs._UniqueIdCounter=1;class ns{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(is||(is={}));class as extends mi{static DefaultMaterialFactory(e){throw(0,re.n)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,re.n)("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case is.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case is.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case is.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return ts.DragMovementThreshold}static set DragMovementThreshold(e){ts.DragMovementThreshold=e}static get LongPressDelay(){return ts.LongPressDelay}static set LongPressDelay(e){ts.LongPressDelay=e}static get DoubleClickDelay(){return ts.DoubleClickDelay}static set DoubleClickDelay(e){ts.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return ts.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){ts.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return R.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,R.Vector4[0].x,R.Vector4[0].y,R.Vector4[0].z):e.setVector4(t,R.Vector4[0])),R.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=l(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=as.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=as.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new ts(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new N(.2,.2,.3,1),this.ambientColor=new L(0,0,0),this.environmentIntensity=1,this._performancePriority=is.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new se.cP,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new se.cP,this._onDisposeObserver=null,this.onBeforeRenderObservable=new se.cP,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new se.cP,this.onAfterRenderCameraObservable=new se.cP,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new se.cP,this.onAfterAnimationsObservable=new se.cP,this.onBeforeDrawPhaseObservable=new se.cP,this.onAfterDrawPhaseObservable=new se.cP,this.onReadyObservable=new se.cP,this.onBeforeCameraRenderObservable=new se.cP,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new se.cP,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new se.cP,this.onAfterActiveMeshesEvaluationObservable=new se.cP,this.onBeforeParticlesRenderingObservable=new se.cP,this.onAfterParticlesRenderingObservable=new se.cP,this.onDataLoadedObservable=new se.cP,this.onNewCameraAddedObservable=new se.cP,this.onCameraRemovedObservable=new se.cP,this.onNewLightAddedObservable=new se.cP,this.onLightRemovedObservable=new se.cP,this.onNewGeometryAddedObservable=new se.cP,this.onGeometryRemovedObservable=new se.cP,this.onNewTransformNodeAddedObservable=new se.cP,this.onTransformNodeRemovedObservable=new se.cP,this.onNewMeshAddedObservable=new se.cP,this.onMeshRemovedObservable=new se.cP,this.onNewSkeletonAddedObservable=new se.cP,this.onSkeletonRemovedObservable=new se.cP,this.onNewMaterialAddedObservable=new se.cP,this.onNewMultiMaterialAddedObservable=new se.cP,this.onMaterialRemovedObservable=new se.cP,this.onMultiMaterialRemovedObservable=new se.cP,this.onNewTextureAddedObservable=new se.cP,this.onTextureRemovedObservable=new se.cP,this.onBeforeRenderTargetsRenderObservable=new se.cP,this.onAfterRenderTargetsRenderObservable=new se.cP,this.onBeforeStepObservable=new se.cP,this.onAfterStepObservable=new se.cP,this.onActiveCameraChanged=new se.cP,this.onActiveCamerasChanged=new se.cP,this.onBeforeRenderingGroupObservable=new se.cP,this.onAfterRenderingGroupObservable=new se.cP,this.onMeshImportedObservable=new se.cP,this.onAnimationFileImportedObservable=new se.cP,this._registeredForLateAnimationBindings=new at(256),this._pointerPickingConfiguration=new ns,this.onPrePointerObservable=new se.cP,this.onPointerObservable=new se.cP,this.onPreKeyboardObservable=new se.cP,this.onKeyboardObservable=new se.cP,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=as.FOGMODE_NONE,this.fogColor=new L(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new M(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new at(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new ss.A,this._activeIndices=new ss.A,this._activeParticles=new ss.A,this._activeBones=new ss.A,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 nt(256),this._processedMaterials=new nt(256),this._renderTargets=new at(256),this._materialsRenderTargets=new at(256),this._activeParticleSystems=new nt(256),this._activeSkeletons=new at(32),this._softwareSkinnedMeshes=new at(32),this._activeAnimatables=new Array,this._transformMatrix=y.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=gi.Create(),this._beforeClearStage=gi.Create(),this._beforeRenderTargetClearStage=gi.Create(),this._gatherRenderTargetsStage=gi.Create(),this._gatherActiveCameraRenderTargetsStage=gi.Create(),this._isReadyForMeshStage=gi.Create(),this._beforeEvaluateActiveMeshStage=gi.Create(),this._evaluateSubMeshStage=gi.Create(),this._preActiveMeshStage=gi.Create(),this._cameraDrawRenderTargetStage=gi.Create(),this._beforeCameraDrawStage=gi.Create(),this._beforeRenderTargetDrawStage=gi.Create(),this._beforeRenderingGroupDrawStage=gi.Create(),this._beforeRenderingMeshStage=gi.Create(),this._afterRenderingMeshStage=gi.Create(),this._afterRenderingGroupDrawStage=gi.Create(),this._afterCameraDrawStage=gi.Create(),this._afterCameraPostProcessStage=gi.Create(),this._afterRenderTargetDrawStage=gi.Create(),this._afterRenderTargetPostProcessStage=gi.Create(),this._afterRenderStage=gi.Create(),this._pointerMoveStage=gi.Create(),this._pointerDownStage=gi.Create(),this._pointerUpStage=gi.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||_.q.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(_.q._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new lt(this),rt&&(this.postProcessManager=new rt(this)),(0,de.BA)()&&this.attachControl(),this._createUbo(),Ii&&(this._imageProcessingConfiguration=new Ii),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 void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const a=s.material||this.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else a.hasRenderTargetTextures&&null!=a.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(a)&&(this._processedMaterials.push(a),this._materialsRenderTargets.concatWithNoDuplicate(a.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}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){void 0!==t?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);-1!==i&&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),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=_e.j.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?ri.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ri.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new qe(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return rs.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._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-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._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(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,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-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||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){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&0!=(t.layerMask&this.activeCamera.layerMask)&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Xe.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(Bi.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(as.MinDeltaTime,Math.min(this._engine.getDeltaTime(),as.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.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 t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){k.V.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),_.q._LastCreatedScene===this&&(this._engine.scenes.length>0?_.q._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:_.q._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;M.CheckExtends(r,t,i),M.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw(0,re.n)("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,a=!1){throw(0,re.n)("Ray")}createPickingRayInCameraSpace(e,t,i){throw(0,re.n)("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw(0,re.n)("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const a=(0,re.n)("Ray",!0);return a&&k.V.Warn(a),new Ni}pickWithBoundingInfo(e,t,i,s,r){const n=(0,re.n)("Ray",!0);return n&&k.V.Warn(n),new Ni}pickWithRay(e,t,i,s){throw(0,re.n)("Ray")}multiPick(e,t,i,s,r){throw(0,re.n)("Ray")}multiPickWithRay(e,t,i){throw(0,re.n)("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(void 0===t)return e;const s=[];for(const r in e){const n=e[r];ae&&ae.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_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,r,n,a){const o=Fe(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_loadFileAsync(e,t,i,s,r){return new Promise(((n,a)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{a(t)}),r)}))}_requestFile(e,t,i,s,r,n,a){const o=we(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_requestFileAsync(e,t,i,s,r){return new Promise(((n,a)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{a(e)}),r)}))}_readFile(e,t,i,s,r){const n=Oe(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw(0,re.n)("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)}}as.FOGMODE_NONE=0,as.FOGMODE_EXP=1,as.FOGMODE_EXP2=2,as.FOGMODE_LINEAR=3,as.MinDeltaTime=1,as.MaxDeltaTime=1e3,d("BABYLON.Scene",as);class os{static AdditionalUV1Kind="additionalUv1";static AdditionalUV2Kind="additionalUv2";static AdditionalUV3Kind="additionalUv3";static AdditionalUV4Kind="additionalUv4";static MatricesSdefCKind="matricesSdefC";static MatricesSdefR0Kind="matricesSdefR0";static MatricesSdefR1Kind="matricesSdefR1";static EdgeScaleKind="edgeScale"}const hs="\n#ifndef SDEFDECLARATION\n#define SDEFDECLARATION\n#if NUM_BONE_INFLUENCERS>0 && defined(SDEF)\nattribute vec3 matricesSdefC;attribute vec3 matricesSdefR0;attribute vec3 matricesSdefR1;vec4 rotationMatrixToQuaternion(mat3 matrix) {float trace=matrix[0][0]+matrix[1][1]+matrix[2][2];float s;float sqrtParam;if (trace>0.0) {sqrtParam=trace+1.0;} else if (matrix[0][0]>matrix[1][1] && matrix[0][0]>matrix[2][2]) {sqrtParam=1.0+matrix[0][0]-matrix[1][1]-matrix[2][2];} else if (matrix[1][1]>matrix[2][2]) {sqrtParam=1.0+matrix[1][1]-matrix[0][0]-matrix[2][2];} else {sqrtParam=1.0+matrix[2][2]-matrix[0][0]-matrix[1][1];}\nfloat sqrtValue=sqrt(sqrtParam);if (trace>0.0) {s=0.5/sqrtValue;return vec4(\n(matrix[1][2]-matrix[2][1])*s,\n(matrix[2][0]-matrix[0][2])*s,\n(matrix[0][1]-matrix[1][0])*s,\n0.25/s\n);} else if (matrix[0][0]>matrix[1][1] && matrix[0][0]>matrix[2][2]) {s=2.0*sqrtValue;return vec4(\n0.25*s,\n(matrix[0][1]+matrix[1][0])/s,\n(matrix[2][0]+matrix[0][2])/s,\n(matrix[1][2]-matrix[2][1])/s\n);} else if (matrix[1][1]>matrix[2][2]) {s=2.0*sqrtValue;return vec4(\n(matrix[0][1]+matrix[1][0])/s,\n0.25*s,\n(matrix[1][2]+matrix[2][1])/s,\n(matrix[2][0]-matrix[0][2])/s\n);} else {s=2.0*sqrtValue;return vec4(\n(matrix[2][0]+matrix[0][2])/s,\n(matrix[1][2]+matrix[2][1])/s,\n0.25*s,\n(matrix[0][1]-matrix[1][0])/s\n);}}\nmat3 quaternionToRotationMatrix(vec4 q) {float xx=q.x*q.x;float yy=q.y*q.y;float zz=q.z*q.z;float xy=q.x*q.y;float zw=q.z*q.w;float zx=q.z*q.x;float yw=q.y*q.w;float yz=q.y*q.z;float xw=q.x*q.w;return mat3(\n1.0-2.0*(yy+zz),2.0*(xy+zw),2.0*(zx-yw),\n2.0*(xy-zw),1.0-2.0*(zz+xx),2.0*(yz+xw),\n2.0*(zx+yw),2.0*(yz-xw),1.0-2.0*(yy+xx)\n);}\nvec4 slerp(vec4 q0,vec4 q1,float t) {float cosTheta=dot(q0,q1);q1=mix(-q1,q1,step(0.0,cosTheta));cosTheta=abs(cosTheta);if (cosTheta>0.999999) {return normalize(mix(q0,q1,t));}\nfloat theta=acos(cosTheta);float sinTheta=sin(theta);float w0=sin((1.0-t)*theta)/sinTheta;float w1=sin(t*theta)/sinTheta;return q0*w0+q1*w1;}\n#endif\n#endif\n",ls="\n#ifndef SDEFVERTEX\n#define SDEFVERTEX\n#if !defined(BAKED_VERTEX_ANIMATION_TEXTURE) && defined(SDEF)\n#if NUM_BONE_INFLUENCERS>0\n{float weight0=matricesWeights[0];float weight1=matricesWeights[1];\n#ifdef BONETEXTURE\nmat4 transformMatrix0=readMatrixFromRawSampler(boneSampler,matricesIndices[0]);mat4 transformMatrix1=readMatrixFromRawSampler(boneSampler,matricesIndices[1]);\n#else\nmat4 transformMatrix0=mBones[int(matricesIndices[0])];mat4 transformMatrix1=mBones[int(matricesIndices[1])];\n#endif\nmat3 slerpedRotationMatrix=quaternionToRotationMatrix(slerp(\nrotationMatrixToQuaternion(mat3(transformMatrix0)),\nrotationMatrixToQuaternion(mat3(transformMatrix1)),\nweight1\n));mat4 sdefInflunce=mat4(\nvec4(1.0,0.0,0.0,0.0),\nvec4(0.0,1.0,0.0,0.0),\nvec4(0.0,0.0,1.0,0.0),\nvec4(-matricesSdefC,1.0)\n);mat4 rotationMatrix=mat4(\nvec4(slerpedRotationMatrix[0],0.0),\nvec4(slerpedRotationMatrix[1],0.0),\nvec4(slerpedRotationMatrix[2],0.0),\nvec4(0.0,0.0,0.0,1.0)\n);sdefInflunce=rotationMatrix*sdefInflunce;vec3 positionOffset =\nvec3(transformMatrix0*vec4(matricesSdefR0,1))*weight0 +\nvec3(transformMatrix1*vec4(matricesSdefR1,1))*weight1;sdefInflunce[3]+=vec4(positionOffset,0.0);float useLinearDeform=step(0.0,-abs(matricesSdefR0.x));influence=mat4(\nmix(sdefInflunce[0],influence[0],useLinearDeform),\nmix(sdefInflunce[1],influence[1],useLinearDeform),\nmix(sdefInflunce[2],influence[2],useLinearDeform),\nmix(sdefInflunce[3],influence[3],useLinearDeform)\n);}\n#endif\n#endif\n#endif\n";class cs{static OverrideEngineCreateEffect(e){const t=e.createEffect.bind(e);e.createEffect=function(e,i,s,r,n,a,o,h,l,c=yt.w.GLSL){let d;if(d=i.attributes?i:{attributes:i,uniformsNames:s,uniformBuffersNames:[],samplers:r??[],defines:n??"",fallbacks:a??null,onCompiled:o??null,onError:h??null,indexParameters:l??null,shaderLanguage:c},(d.shaderLanguage===yt.w.GLSL||void 0===d.shaderLanguage)&&(d.uniformsNames.includes("mBones")||d.samplers.includes("boneSampler"))&&-1===d.defines.indexOf("#define SDEF")){d.attributes.push(os.MatricesSdefCKind),d.attributes.push(os.MatricesSdefR0Kind),d.attributes.push(os.MatricesSdefR1Kind),d.defines+="\n#define SDEF";const e=d.processCodeAfterIncludes;d.processCodeAfterIncludes=e?function(t,i){return i=e(t,i),cs.ProcessSdefCode(t,i)}:cs.ProcessSdefCode}return t(e,d,this)}}static ProcessSdefCode(e,t){if("vertex"!==e)return t;const i="#define CUSTOM_VERTEX_DEFINITIONS";if(t.includes(i))t=t.replace(i,`${i}\n${hs}`);else{const e="void main() {";t=t.replace(e,`${hs}\nvoid main() {`)}const s=new RegExp("finalWorld=finalWorld\\*influence;","g");return t.replace(s,`${ls}\nfinalWorld=finalWorld*influence;`)}}_t.M.RegisterShader("mmdOutline","\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n","\nattribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform vec2 viewport;uniform mat3 view;uniform mat4 viewProjection;\n#ifdef WORLDPOS_REQUIRED\nuniform mat4 inverseViewProjection;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec3 viewNormal=view*(mat3(finalWorld)*normalUpdated);vec4 projectedPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vec2 screenNormal=normalize(vec2(viewNormal));projectedPosition.xy+=screenNormal/(viewport*0.25/*0.5 */)*offset*projectedPosition.w;gl_Position=projectedPosition;\n#ifdef WORLDPOS_REQUIRED\nvec4 worldPos=inverseViewProjection*projectedPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n"),as.prototype.getMmdOutlineRenderer=function(){return this._mmdOutlineRenderer||(this._mmdOutlineRenderer=new ds(this)),this._mmdOutlineRenderer};class ds{name="MmdOutline";scene;_engine;_passIdForDrawWrapper;constructor(e){this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=this._engine.createRenderPassId("Mmd Outline Renderer")}register(){this.scene._afterRenderingMeshStage.registerStep(pi.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){this._engine.releaseRenderPassId(this._passIdForDrawWrapper)}static _ViewMatrix=new Float32Array(9);static _InverseViewProjectionMatrix=new y;render(e,t,i){i=i??this._passIdForDrawWrapper;const s=this.scene,r=s.getEngine(),n=r.getCaps().instancedArrays&&(null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id]||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,n,i))return;const a=e.getMesh(),o=a._internalAbstractMeshDataInfo._actAsRegularMesh?a:null,h=e.getRenderingMesh(),l=o||h,c=e.getMaterial();if(!c||!s.activeCamera)return;const d=e._getDrawWrapper(i),u=pt.GetEffect(d);r.enableEffect(d),c.useLogarithmicDepth&&u.setFloat("logarithmicDepthConstant",2/(Math.log(s.activeCamera.maxZ+1)/Math.LN2)),u.setFloat("offset",c.outlineWidth),u.setColor4("color",c.outlineColor,c.outlineAlpha);const f=r.getRenderHeight(),_=r.getRenderWidth();u.setFloat2("viewport",_,f);const p=ds._ViewMatrix;{const e=s.getViewMatrix().m;p[0]=e[0],p[1]=e[1],p[2]=e[2],p[3]=e[4],p[4]=e[5],p[5]=e[6],p[6]=e[8],p[7]=e[9],p[8]=e[10]}if(u.setMatrix3x3("view",p),u.setMatrix("viewProjection",s.getTransformMatrix()),u.setMatrix("world",l.getWorldMatrix()),Kt(l,u),h.morphTargetManager&&h.morphTargetManager.isUsingTextureForTargets&&h.morphTargetManager._bind(u),Gt(h,u),n||h._bind(e,u,c.fillMode),c&&c.needAlphaTesting()){const e=c.getAlphaTestTexture();e&&(u.setTexture("diffuseSampler",e),u.setMatrix("diffuseMatrix",e.getTextureMatrix()))}Ot(u,c,s),u.defines.includes("WORLDPOS_REQUIRED")&&u.setMatrix("inverseViewProjection",s.getTransformMatrix().invertToRef(ds._InverseViewProjectionMatrix)),h._processRendering(l,e,u,c.fillMode,t,n,((e,t)=>{u.setMatrix("world",t)}))}isReady(e,t,i){i=i??this._passIdForDrawWrapper;const s=[],r=[G.PositionKind,G.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;const o=n.getScene();a.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(G.UVKind)&&(r.push(G.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(G.UV2Kind)&&(r.push(G.UV2Kind),s.push("#define UV2"))),a.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),Dt(a,o,s);let h=!1;for(let e=0;e4&&(r.push(G.MatricesIndicesExtraKind),r.push(G.MatricesWeightsExtraKind)),n.isVerticesDataPresent(os.MatricesSdefCKind)&&(r.push(os.MatricesSdefCKind),r.push(os.MatricesSdefR0Kind),r.push(os.MatricesSdefR1Kind),s.push("#define SDEF"));const e=n.skeleton;s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),n.numBoneInfluencers>0&&l.addCPUSkinningFallback(0,n),e.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(e.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const c=n.morphTargetManager;let d=0;c&&(d=c.numMaxInfluencers||c.numInfluencers,d>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+d),c.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Ut(r,n,d))),t&&(s.push("#define INSTANCES"),Vt(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const u=e._getDrawWrapper(i,!0),f=u.defines,_=s.join("\n");if(f!==_){const e=["world","mBones","viewport","view","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","boneTextureWidth","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"],t=["diffuseSampler","boneSampler","morphTargets"];Pt(e),h&&e.push("inverseViewProjection"),u.setEffect(this.scene.getEngine().createEffect("mmdOutline",{attributes:r,uniformsNames:e,samplers:t,defines:_,indexParameters:{maxSimultaneousMorphTargets:d},processCodeAfterIncludes:cs.ProcessSdefCode},this.scene.getEngine()),_)}return u.effect.isReady()}_afterRenderingMesh(e,t,i){const s=t.getMaterial();if(null!==s&&s.renderOutline){const e=this._engine,s=e.getDepthWrite(),r=e.getAlphaMode();e.setDepthWrite(!0),e.setAlphaMode(Mi.ALPHA_COMBINE,!0),e.setState(!0,void 0,void 0,void 0,!!this.scene._mirroredCameraPosition),this.render(t,i,this._passIdForDrawWrapper),e.setAlphaMode(r,!0),e.setDepthWrite(s)}}}class us{static get ForceFullSceneLoadingForIncremental(){return us._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){us._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return us._ShowLoadingScreen}static set ShowLoadingScreen(e){us._ShowLoadingScreen=e}static get loggingLevel(){return us._LoggingLevel}static set loggingLevel(e){us._LoggingLevel=e}static get CleanBoneMatrixWeights(){return us._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){us._CleanBoneMatrixWeights=e}}var fs,_s,ps,gs,ms;us._ForceFullSceneLoadingForIncremental=!1,us._ShowLoadingScreen=!0,us._CleanBoneMatrixWeights=!1,us._LoggingLevel=0,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(fs||(fs={}));class Ts{static get ForceFullSceneLoadingForIncremental(){return us.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){us.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return us.ShowLoadingScreen}static set ShowLoadingScreen(e){us.ShowLoadingScreen=e}static get loggingLevel(){return us.loggingLevel}static set loggingLevel(e){us.loggingLevel=e}static get CleanBoneMatrixWeights(){return us.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){us.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Ts._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return Ts._RegisteredPlugins[e]||(k.V.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),Ts.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Ts._RegisteredPlugins){const i=Ts._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ts._RegisteredPlugins[t]}return Ts.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Ts._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,a,o){const h=Ts._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const l=a?Ts._GetPluginForExtension(a):h?Ts._GetPluginForDirectLoad(e.url):Ts._GetPluginForFilename(e.url);if(e.rawData&&!l.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==l.plugin.createPlugin?l.plugin.createPlugin():l.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(Ts.OnPluginActivatedObservable.notifyObservers(c),h&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!Ne(e.url))){if(c.directLoad){const e=c.directLoad(t,h);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,h);return c}const d=l.isBinary,u=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let f=null,_=!1;const p=c.onDisposeObservable;p&&p.add((()=>{_=!0,f&&(f.abort(),f=null),n()}));const g=()=>{if(_)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";f=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,u,s,d,i,o):t._loadFile(e.file||e.url,u,s,!0,d,i)},m=t.getEngine();let T=m.enableOfflineSupport;if(T){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}T=!i}return T&&Ai.N.OfflineProviderFactory?t.offlineProvider=Ai.N.OfflineProviderFactory(e.url,g,m.disableManifestCheck):g(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=ze(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return Xe.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=Xe.GetFilename(e),e=Xe.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Ts._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Ts._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Ts._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Ts._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=_.q.LastCreatedScene,r=null,n=null,a=null,o=null,h=""){if(!s)return k.V.Error("No scene available to import mesh to"),null;const l=Ts._GetFileInfo(t,i);if(!l)return null;const c={};s.addPendingData(c);const d=()=>{s.removePendingData(c)},u=(e,t)=>{const i=Ts._FormatErrorMessage(l,e,t);a?a(s,i,new xe(i,Te,t)):k.V.Error(i),d()},f=n?e=>{try{n(e)}catch(e){u("Error in onProgress callback: "+e,e)}}:void 0,p=(e,t,i,n,a,o,h,d)=>{if(s.importedMeshesFiles.push(l.url),r)try{r(e,t,i,n,a,o,h,d)}catch(e){u("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return Ts._LoadData(l,s,((t,i,r)=>{if(t.rewriteRootURL&&(l.rootUrl=t.rewriteRootURL(l.rootUrl,r)),t.importMesh){const r=[],n=[],a=[];if(!t.importMesh(e,s,i,l.rootUrl,r,n,a,u))return;s.loadingPluginName=t.name,p(r,n,a,[],[],[],[],[])}else t.importMeshAsync(e,s,i,l.rootUrl,f,l.name).then((e=>{s.loadingPluginName=t.name,p(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{u(e.message,e)}))}),f,u,d,o,h)}static ImportMeshAsync(e,t,i="",s=_.q.LastCreatedScene,r=null,n=null,a=""){return new Promise(((o,h)=>{Ts.ImportMesh(e,t,i,s,((e,t,i,s,r,n,a,h)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:a,spriteManagers:h})}),r,((e,t,i)=>{h(i||new Error(t))}),n,a)}))}static Load(e,t="",i=_.q.LastCreatedEngine,s=null,r=null,n=null,a=null,o=""){return i?Ts.Append(e,t,new as(i),s,r,n,a,o):(Xe.Error("No engine available"),null)}static LoadAsync(e,t="",i=_.q.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((a,o)=>{Ts.Load(e,t,i,(e=>{a(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r,n)}))}static Append(e,t="",i=_.q.LastCreatedScene,s=null,r=null,n=null,a=null,o=""){if(!i)return k.V.Error("No scene available to append to"),null;const h=Ts._GetFileInfo(e,t);if(!h)return null;const l={};i.addPendingData(l);const c=()=>{i.removePendingData(l)};Ts.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const d=(e,t)=>{const s=Ts._FormatErrorMessage(h,e,t);n?n(i,s,new xe(s,Te,t)):k.V.Error(s),c()},u=r?e=>{try{r(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=()=>{if(s)try{s(i)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(l)};return Ts._LoadData(h,i,((e,t)=>{if(e.load){if(!e.load(i,t,h.rootUrl,d))return;i.loadingPluginName=e.name,f()}else e.loadAsync(i,t,h.rootUrl,u,h.name).then((()=>{i.loadingPluginName=e.name,f()})).catch((e=>{d(e.message,e)}))}),u,d,c,a,o)}static AppendAsync(e,t="",i=_.q.LastCreatedScene,s=null,r=null,n=""){return new Promise(((a,o)=>{Ts.Append(e,t,i,(e=>{a(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=_.q.LastCreatedScene,s=null,r=null,n=null,a=null,o=""){if(!i)return k.V.Error("No scene available to load asset container to"),null;const h=Ts._GetFileInfo(e,t);if(!h)return null;const l={};i.addPendingData(l);const c=()=>{i.removePendingData(l)},d=(e,t)=>{const s=Ts._FormatErrorMessage(h,e,t);n?n(i,s,new xe(s,Te,t)):k.V.Error(s),c()},u=r?e=>{try{r(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=e=>{if(s)try{s(e)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(l)};return Ts._LoadData(h,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,h.rootUrl,d);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,f(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,h.rootUrl,u,h.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,f(t)})).catch((e=>{d(e.message,e)})):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),u,d,c,a,o)}static LoadAssetContainerAsync(e,t="",i=_.q.LastCreatedScene,s=null,r=null){return new Promise(((n,a)=>{Ts.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=_.q.LastCreatedScene,s=!0,r=fs.Clean,n=null,a=null,o=null,h=null,l=null){if(!i)return void k.V.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case fs.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case fs.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case fs.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case fs.NoSync:break;default:return void k.V.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)}),o,h,l)}static ImportAnimationsAsync(e,t="",i=_.q.LastCreatedScene,s=!0,r=fs.Clean,n=null,a=null,o=null,h=null,l=null){return new Promise(((a,h)=>{Ts.ImportAnimations(e,t,i,s,r,n,(e=>{a(e)}),o,((e,t,i)=>{h(i||new Error(t))}),l)}))}}Ts.NO_LOGGING=0,Ts.MINIMAL_LOGGING=1,Ts.SUMMARY_LOGGING=2,Ts.DETAILED_LOGGING=3,Ts.OnPluginActivatedObservable=new se.cP,Ts._RegisteredPlugins={},Ts._ShowingLoadingScreen=!1;class xs{log(e){console.log(e)}warn(e){console.warn(e)}error(e){console.error(e)}}class Es{isDeviceLittleEndian;_dataView;_decoder;_offset;constructor(e){this.isDeviceLittleEndian=this._getIsDeviceLittleEndian(),this._dataView=new DataView(e),this._decoder=null,this._offset=0}get offset(){return this._offset}set offset(e){this._offset=e}_getIsDeviceLittleEndian(){const e=new Int16Array([256]);return 1===new Int8Array(e.buffer)[1]}swap16Array(e){for(let t=0;t>8&255}}swap32Array(e){for(let t=0;t>8&65280|i>>24&255}}getUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}getInt8(){const e=this._dataView.getInt8(this._offset);return this._offset+=1,e}getUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);e.set(t),this._offset+=e.byteLength}getUint16(){const e=this._dataView.getUint16(this._offset,!0);return this._offset+=2,e}getUint16Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap16Array(e)}getInt16(){const e=this._dataView.getInt16(this._offset,!0);return this._offset+=2,e}getUint32(){const e=this._dataView.getUint32(this._offset,!0);return this._offset+=4,e}getUint32Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap32Array(e)}getInt32(){const e=this._dataView.getInt32(this._offset,!0);return this._offset+=4,e}getInt32Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap32Array(e)}getFloat32(){const e=this._dataView.getFloat32(this._offset,!0);return this._offset+=4,e}getFloat32Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap32Array(e)}getFloat32Tuple(e){const t=new Array(e);for(let i=0;i0&&t.warn(`There are ${i.bytesAvailable} bytes left after parsing`),{header:s,vertices:r,indices:n,textures:u,materials:f,bones:p,morphs:l,displayFrames:c,rigidBodies:_,joints:g,softBodies:[]}}static _ParseHeader(e){if(e.bytesAvailable<7)throw new Error("is not pmd file");const t=e.getSignatureString(3);if("Pmd"!==t)throw new Error("is not pmd file");const i=e.getFloat32(),s=e.getDecoderString(20,!0),r=e.getDecoderString(256,!0);return{signature:t,version:i,encoding:ps.Header.Encoding.ShiftJis,additionalVec4Count:0,vertexIndexSize:2,textureIndexSize:4,materialIndexSize:4,boneIndexSize:2,morphIndexSize:2,rigidBodyIndexSize:4,modelName:s,englishModelName:"",comment:r,englishComment:""}}static async _ParseVerticesAsync(e){const t=e.getUint32(),i=[];let s=performance.now();for(let r=0;rsetTimeout(e,0))),s=performance.now())}return i}static _ParseIndices(e){const t=e.getUint32(),i=new Uint16Array(t);return e.getUint16Array(i),i}static _ParseMaterials(e){const t=e.getUint32(),i=[];for(let s=0;sl[e+1][1]){c=!1;break}if(!c){l.sort(((e,t)=>e[1]-t[1]));const e=new Array(l.length);for(let t=1;tl[t][0]||void 0!==e[t-1])&&(i=!1),i||(e[t]=a[l[t-1][0]])}const t=new Map;for(let i=0;i{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function Ms(e,t,i,s,r){const n=()=>{let a;const o=e=>{e.done?i(e.value):void 0===a?a=!0:n()};do{a=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,o,s),void 0===a&&(a=!1)}while(a)};n()}function bs(e,t){let i;return Ms(e,As,(e=>i=e),(e=>{throw e}),t),i}class Ss{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class ys{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let a=i;a!Array.isArray(e)&&!Array.isArray(t)))],ys,"extractMinAndMaxIndexed",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],ys,"extractMinAndMax",null);class Rs{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new pt(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,a,o=!0){return new Rs(e,t,i,s,r,n,a,o)}constructor(e,t,i,s,r,n,a,o=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,h&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,o&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&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(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(G.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=function(e,t,i,s,r=null){const n=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new M(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return ys.extractMinAndMaxIndexed(e,t,i,s,n,a),r&&(n.x-=n.x*r.x+r.y,n.y-=n.y*r.x+r.y,n.z-=n.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:n,maximum:a}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new si(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)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}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 t=this.indexStart;to&&(o=t)}return new Rs(e,a,o-a+1,t,i,s,r,n)}}class Cs{}class Ps{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>bs(e(...t),undefined)),this.uniqueId=Ps._UniqueIDGenerator,Ps._UniqueIDGenerator++}set(e,t){switch(e.length||k.V.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case G.PositionKind:this.positions=e;break;case G.NormalKind:this.normals=e;break;case G.TangentKind:this.tangents=e;break;case G.UVKind:this.uvs=e;break;case G.UV2Kind:this.uvs2=e;break;case G.UV3Kind:this.uvs3=e;break;case G.UV4Kind:this.uvs4=e;break;case G.UV5Kind:this.uvs5=e;break;case G.UV6Kind:this.uvs6=e;break;case G.ColorKind:this.colors=e;break;case G.MatricesIndicesKind:this.matricesIndices=e;break;case G.MatricesWeightsKind:this.matricesWeights=e;break;case G.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case G.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}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(G.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(G.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(G.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(G.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(G.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(G.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(G.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(G.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(G.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(G.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(G.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(G.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(G.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(G.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 t=e;t.subMeshes=[];for(const e of this.materialInfos)new Rs(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(G.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(G.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(G.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(G.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(G.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(G.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(G.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(G.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(G.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(G.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(G.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(G.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(G.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(G.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=R.Vector3[0],n=R.Vector3[1];for(let a=i;a({vertexData:e}))):[{vertexData:e}];return bs(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,a=!1){this._validate();let o=t.map((e=>e.vertexData)),h=this;if(a)for(const e of o)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of o)if(e)if(a)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let a=null;const l=[];for(const t of this.splitBasedOnMaterialID())l.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())l.push({vertexData:t,transform:e.transform});l.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of l){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{const e=new Cs;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),a=e}s+=t.indices.length,r+=t.positions.length/3}const c=l.splice(0,1)[0];h=c.vertexData,e=c.transform,o=l.map((e=>e.vertexData)),t=l,this.materialInfos=n}const l=o.reduce(((e,t)=>e+(t.indices?.length??0)),h.indices?.length??0);let c=r||o.some((e=>e.indices===h.indices))?h.indices?.slice():h.indices;if(l>0){let r=c?.length??0;if(c||(c=new Array(l)),c.length!==l){if(Array.isArray(c))c.length=l;else{const e=i||c instanceof Uint32Array?new Uint32Array(l):new Uint16Array(l);e.set(c),c=e}e&&e.determinant()<0&&Ps._FlipFaces(c,0,r)}let n=h.positions?h.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),h.normals&&(this.normals=Ps._MergeElement(G.NormalKind,h.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),h.tangents&&(this.tangents=Ps._MergeElement(G.TangentKind,h.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),h.uvs&&(this.uvs=Ps._MergeElement(G.UVKind,h.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),h.uvs2&&(this.uvs2=Ps._MergeElement(G.UV2Kind,h.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),h.uvs3&&(this.uvs3=Ps._MergeElement(G.UV3Kind,h.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),h.uvs4&&(this.uvs4=Ps._MergeElement(G.UV4Kind,h.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),h.uvs5&&(this.uvs5=Ps._MergeElement(G.UV5Kind,h.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),h.uvs6&&(this.uvs6=Ps._MergeElement(G.UV6Kind,h.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),h.colors&&(this.colors=Ps._MergeElement(G.ColorKind,h.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==h.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=h.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),h.matricesIndices&&(this.matricesIndices=Ps._MergeElement(G.MatricesIndicesKind,h.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),h.matricesWeights&&(this.matricesWeights=Ps._MergeElement(G.MatricesWeightsKind,h.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),h.matricesIndicesExtra&&(this.matricesIndicesExtra=Ps._MergeElement(G.MatricesIndicesExtraKind,h.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),h.matricesWeightsExtra&&(this.matricesWeightsExtra=Ps._MergeElement(G.MatricesWeightsExtraKind,h.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),a=e===G.PositionKind?Ps._TransformVector3Coordinates:e===G.NormalKind?Ps._TransformVector3Normals:e===G.TangentKind?Ps._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&a(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&a(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=G.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(G.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(G.NormalKind,this.normals),this.tangents&&i(G.TangentKind,this.tangents),this.uvs&&i(G.UVKind,this.uvs),this.uvs2&&i(G.UV2Kind,this.uvs2),this.uvs3&&i(G.UV3Kind,this.uvs3),this.uvs4&&i(G.UV4Kind,this.uvs4),this.uvs5&&i(G.UV5Kind,this.uvs5),this.uvs6&&i(G.UV6Kind,this.uvs6),this.colors&&i(G.ColorKind,this.colors),this.matricesIndices&&i(G.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(G.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(G.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(G.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Ps.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 Ps._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Ps._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Ps;return e.isVerticesDataPresent(G.PositionKind)&&(s.positions=e.getVerticesData(G.PositionKind,t,i)),e.isVerticesDataPresent(G.NormalKind)&&(s.normals=e.getVerticesData(G.NormalKind,t,i)),e.isVerticesDataPresent(G.TangentKind)&&(s.tangents=e.getVerticesData(G.TangentKind,t,i)),e.isVerticesDataPresent(G.UVKind)&&(s.uvs=e.getVerticesData(G.UVKind,t,i)),e.isVerticesDataPresent(G.UV2Kind)&&(s.uvs2=e.getVerticesData(G.UV2Kind,t,i)),e.isVerticesDataPresent(G.UV3Kind)&&(s.uvs3=e.getVerticesData(G.UV3Kind,t,i)),e.isVerticesDataPresent(G.UV4Kind)&&(s.uvs4=e.getVerticesData(G.UV4Kind,t,i)),e.isVerticesDataPresent(G.UV5Kind)&&(s.uvs5=e.getVerticesData(G.UV5Kind,t,i)),e.isVerticesDataPresent(G.UV6Kind)&&(s.uvs6=e.getVerticesData(G.UV6Kind,t,i)),e.isVerticesDataPresent(G.ColorKind)&&(s.colors=e.getVerticesData(G.ColorKind,t,i)),e.isVerticesDataPresent(G.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(G.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(G.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(G.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(G.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(G.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(G.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(G.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw(0,re.n)("ribbonBuilder")}static CreateBox(e){throw(0,re.n)("boxBuilder")}static CreateTiledBox(e){throw(0,re.n)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,re.n)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,re.n)("sphereBuilder")}static CreateCylinder(e){throw(0,re.n)("cylinderBuilder")}static CreateTorus(e){throw(0,re.n)("torusBuilder")}static CreateLineSystem(e){throw(0,re.n)("linesBuilder")}static CreateDashedLines(e){throw(0,re.n)("linesBuilder")}static CreateGround(e){throw(0,re.n)("groundBuilder")}static CreateTiledGround(e){throw(0,re.n)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,re.n)("groundBuilder")}static CreatePlane(e){throw(0,re.n)("planeBuilder")}static CreateDisc(e){throw(0,re.n)("discBuilder")}static CreatePolygon(e,t,i,s,r,n,a){throw(0,re.n)("polygonBuilder")}static CreateIcoSphere(e){throw(0,re.n)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,re.n)("polyhedronBuilder")}static CreateCapsule(e={orientation:M.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,re.n)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,re.n)("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,a=0,o=0,h=0,l=0,c=0,d=0,u=0,f=0,_=0,p=0,g=0,m=0,T=0,x=0,E=0,v=0,A=0,b=0,S=!1,y=!1,I=!1,R=!1,C=1,P=0,D=null;s&&(S=!!s.facetNormals,y=!!s.facetPositions,I=!!s.facetPartitioning,C=!0===s.useRightHandedSystem?-1:1,P=s.ratio||0,R=!!s.depthSort,D=s.distanceTo,R&&void 0===D&&(D=M.Zero()));let O=0,F=0,w=0,L=0;for(I&&s&&s.bbSize&&(O=s.subDiv.X*P/s.bbSize.x,F=s.subDiv.Y*P/s.bbSize.y,w=s.subDiv.Z*P/s.bbSize.z,L=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],Ps,"_TransformVector3Coordinates",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],Ps,"_TransformVector3Normals",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],Ps,"_TransformVector4Normals",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],Ps,"_FlipFaces",null);class Ds{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 Ds(Ds.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||_.q.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._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 r=new G(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}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 r=this._meshes,n=r.length;if(s===G.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new M(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}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);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&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(G.PositionKind)))return;this._extend=Is(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===G.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&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 e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Ps;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(G.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(G.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(G.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(G.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(G.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(G.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(G.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(G.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(G.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(G.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Ds._CleanMatricesWeights(e,t),t.setVerticesData(G.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(G.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(G.MatricesIndicesKind),n=t.getVerticesData(G.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,l=a.length;for(let e=0;eh-1)&&(l=h-1),t>i){const i=1/t;for(let t=0;t<4;t++)a[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else l>=4?(o[e+l-4]=1-t,n[e+l-4]=s):(a[e+l]=1-t,r[e+l]=s)}t.setVerticesData(G.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(G.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new Ds(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,ae&&ae.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new si(M.FromArray(e.boundingBoxMinimum),M.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(G.UVKind),e.hasUVs2&&s._delayInfo.push(G.UV2Kind),e.hasUVs3&&s._delayInfo.push(G.UV3Kind),e.hasUVs4&&s._delayInfo.push(G.UV4Kind),e.hasUVs5&&s._delayInfo.push(G.UV5Kind),e.hasUVs6&&s._delayInfo.push(G.UV6Kind),e.hasColors&&s._delayInfo.push(G.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(G.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(G.MatricesWeightsKind),s._delayLoadingFunction=Ps.ImportVertexData):Ps.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(gs||(gs={}));class Os{}Os.X=new M(1,0,0),Os.Y=new M(0,1,0),Os.Z=new M(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(ms||(ms={}));const Fs=y.Compose(M.One(),S.FromEulerAngles(0,Math.PI,0),M.Zero());class ws extends ce{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=0!=(this._billboardMode&ws.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==ws.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 M(0,0,1),this._up=new M(0,1,0),this._right=new M(1,0,0),this._position=M.Zero(),this._rotation=M.Zero(),this._rotationQuaternion=null,this._scaling=M.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=ws.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=y.Zero(),this._usePivotMatrix=!1,this._absolutePosition=M.Zero(),this._absoluteScaling=M.Zero(),this._absoluteRotationQuaternion=S.Identity(),this._pivotMatrix=y.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new se.cP,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return M.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return M.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return M.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=y.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==ws.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=y.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 e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||S.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(void 0===e.x){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 e=R.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),M.TransformCoordinatesFromFloatsToRef(t,i,s,e,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=M.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=R.Matrix[0];return this._localMatrix.invertToRef(e),M.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=M.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=gs.LOCAL){const n=ws._LookAtVectorCache,a=r===gs.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,i,s),r===gs.WORLD&&this.parent)if(this.rotationQuaternion){const e=R.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=R.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=R.Quaternion[0];S.FromEulerVectorToRef(this.rotation,e);const t=R.Matrix[0];e.toRotationMatrix(t);const i=R.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=M.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return M.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?S.RotationYawPitchRollToRef(r+t,a+i,s,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=gs.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==gs.WORLD){const t=R.Matrix[0];i.invertToRef(t),e=M.TransformCoordinates(e,t)}return this.setPivotMatrix(y.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=M.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=M.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),M.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=R.Quaternion[0],r=R.Vector3[0],n=R.Vector3[1],a=R.Matrix[1];y.IdentityToRef(a);const o=R.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=ws._TmpRotation,S.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),y.ComposeToRef(this.scaling,h,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(a),o.multiplyToRef(a,o)),o.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(y.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(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,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==gs.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=R.Matrix[0];i.invertToRef(s),e=M.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=S.RotationAxisToRef(e,t,ws._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=S.RotationAxisToRef(e,t,ws._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=S.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=R.Vector3[0],r=R.Vector3[1],n=R.Vector3[2],a=R.Quaternion[0],o=R.Matrix[0],h=R.Matrix[1],l=R.Matrix[2],c=R.Matrix[3];return e.subtractToRef(this.position,s),y.TranslationToRef(s.x,s.y,s.z,o),y.TranslationToRef(-s.x,-s.y,-s.z,h),y.RotationAxisToRef(t,i,l),h.multiplyToRef(l,c),c.multiplyToRef(o,c),c.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==gs.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=R.Quaternion[1],S.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=R.Quaternion[0];return S.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==ws.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=ws._TmpScaling;let a,o=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new M(e.m[12],e.m[13],e.m[14]);o=ws._TmpTranslation,o.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,a=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(S.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(a=ws._TmpRotation,S.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a)),this._usePivotMatrix){const e=R.Matrix[1];y.ScalingToRef(n.x,n.y,n.z,e);const t=R.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,R.Matrix[4]),R.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else y.ComposeToRef(n,a,o,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),R.Matrix[7])}else R.Matrix[7].copyFrom(r.getWorldMatrix());const e=R.Vector3[5],t=R.Vector3[6],i=R.Quaternion[0];R.Matrix[7].decompose(t,i,e),y.ScalingToRef(t.x,t.y,t.z,R.Matrix[7]),R.Matrix[7].setTranslation(e),ws.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(R.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),R.Matrix[6]),R.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=R.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),R.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&R.Matrix[1].multiplyToRef(Fs,R.Matrix[1]),R.Matrix[1].setTranslationFromFloats(0,0,0),R.Matrix[1].invertToRef(R.Matrix[0]),(this.billboardMode&ws.BILLBOARDMODE_ALL)!==ws.BILLBOARDMODE_ALL){R.Matrix[0].decompose(void 0,R.Quaternion[0],void 0);const e=R.Vector3[1];R.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&ws.BILLBOARDMODE_X)!==ws.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&ws.BILLBOARDMODE_Y)!==ws.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&ws.BILLBOARDMODE_Z)!==ws.BILLBOARDMODE_Z&&(e.z=0),y.RotationYawPitchRollToRef(e.y,e.x,e.z,R.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(R.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(R.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=R.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(R.Matrix[1]);const s=R.Vector3[1];M.TransformCoordinatesToRef(i,R.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),a=-Math.atan2(s.y,n);if(S.RotationYawPitchRollToRef(r,a,0,R.Quaternion[0]),(this.billboardMode&ws.BILLBOARDMODE_ALL)!==ws.BILLBOARDMODE_ALL){const e=R.Vector3[1];R.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&ws.BILLBOARDMODE_X)!==ws.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&ws.BILLBOARDMODE_Y)!==ws.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&ws.BILLBOARDMODE_Z)!==ws.BILLBOARDMODE_Z&&(e.z=0),y.RotationYawPitchRollToRef(e.y,e.x,e.z,R.Matrix[0])}else y.FromQuaternionToRef(R.Quaternion[0],R.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(R.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(R.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=y.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew ws(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew ws(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(y.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(y.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof ws)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);if(0===o)return this;const h=1/o;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}ws.BILLBOARDMODE_NONE=0,ws.BILLBOARDMODE_X=1,ws.BILLBOARDMODE_Y=2,ws.BILLBOARDMODE_Z=4,ws.BILLBOARDMODE_ALL=7,ws.BILLBOARDMODE_USE_POSITION=128,ws.BillboardUseParentOrientation=!1,ws._TmpRotation=S.Zero(),ws._TmpScaling=M.Zero(),ws._TmpTranslation=M.Zero(),ws._LookAtVectorCache=new M(0,0,0),ws._RotationAxisCache=new S,z([J("position")],ws.prototype,"_position",void 0),z([J("rotation")],ws.prototype,"_rotation",void 0),z([K(10,"rotationQuaternion")],ws.prototype,"_rotationQuaternion",void 0),z([J("scaling")],ws.prototype,"_scaling",void 0),z([q("billboardMode")],ws.prototype,"_billboardMode",void 0),z([q()],ws.prototype,"scalingDeterminant",void 0),z([q("infiniteDistance")],ws.prototype,"_infiniteDistance",void 0),z([q()],ws.prototype,"ignoreNonUniformScaling",void 0),z([q()],ws.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Ls{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new M(0,0,0),this._diffPositionForCollisions=new M(0,0,0),this._collisionResponse=!0}}class Ns{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=M.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Bs{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Ns,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 Ls,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Us extends ws{static get BILLBOARDMODE_NONE(){return ws.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return ws.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return ws.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return ws.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return ws.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return ws.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)}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,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Bs,this._waitingMaterialId=null,this.cullingStrategy=Us.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new se.cP,this.onCollisionPositionChangeObservable=new se.cP,this.onMaterialChangedObservable=new se.cP,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=L.Red(),this.outlineWidth=.02,this.overlayColor=L.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 M(.5,1,.5),this.ellipsoidOffset=new M(0,0,0),this.edgesWidth=1,this.edgesColor=new N(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new se.cP,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ai.N.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new qe(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case is.Aggressive:this.doNotSyncBoundingInfo=!0;case is.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_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: "+("InstancedMesh"!==this.getClassName()?"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!==ws.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._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(-1===i){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);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new si(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(G.MatricesIndicesKind)&&this.isVerticesDataPresent(G.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===ws.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 y;(this.rotationQuaternion?this.rotationQuaternion:S.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=M.Zero(),n=this.definedFacingForward?-1:1;return M.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,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 M(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=Is(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new si(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(G.MatricesIndicesExtraKind):null,a=r?this.getVerticesData(G.MatricesWeightsExtraKind):null,o=this.skeleton.getTransformMatrices(this),h=R.Vector3[0],l=R.Matrix[0],c=R.Matrix[1];let d=0;for(let u=0;u0&&(y.FromFloat32ArrayToRefScaled(o,Math.floor(16*e[d+f]),_,c),l.addToSelf(c));if(r)for(f=0;f<4;f++)_=a[d+f],_>0&&(y.FromFloat32ArrayToRefScaled(o,Math.floor(16*n[d+f]),_,c),l.addToSelf(c));s===G.NormalKind?M.TransformNormalFromFloatsToRef(i[u],i[u+1],i[u+2],l,h):M.TransformCoordinatesFromFloatsToRef(i[u],i[u+1],i[u+2],l,h),h.toArray(i,u),s===G.PositionKind&&this._positions&&this._positions[u/3].copyFrom(h)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,G.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,G.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(G.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.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 t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=R.Matrix[0],i=R.Matrix[1];return y.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const a=new Ni,o=this.getClassName(),h="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,l=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(n||e.intersectsSphere(l.boundingSphere,h)&&e.intersectsBox(l.boundingBox,h)))return a;if(s)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:M.Distance(e.origin,l.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let c=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),u=d.length;let f=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const a=r.intersects(e,this._positions,this.getIndices(),t,i);if(a&&(t||!c||a.distancee!==this&&e.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 t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:M.Zero()}e.depthSortedFacets=[];for(let t=0;ta?r.maximum.x-r.minimum.x:a,e.bbSize.y=r.maximum.y-r.minimum.y>a?r.maximum.y-r.minimum.y:a,e.bbSize.z=r.maximum.z-r.minimum.z>a?r.maximum.z-r.minimum.z:a;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),M.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Ps.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||a<0||a>r.subDiv.max||o<0||o>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const a=this.getWorldMatrix(),o=R.Matrix[5];a.invertToRef(o);const h=R.Vector3[8];M.TransformCoordinatesFromFloatsToRef(e,t,i,o,h);const l=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,r,n);return s&&M.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,a,s),l}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let a=null,o=0,h=0,l=0,c=0,d=0,u=0,f=0,_=0;const p=this.getFacetLocalPositions(),g=this.getFacetLocalNormals(),m=this.getFacetsAtLocalCoordinates(e,t,i);if(!m)return null;let T,x,E,v=Number.MAX_VALUE,A=v;for(let M=0;M=0||r&&!n&&c<=0)&&(c=x.x*E.x+x.y*E.y+x.z*E.z,d=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),u=e+x.x*d,f=t+x.y*d,_=i+x.z*d,o=u-e,h=f-t,l=_-i,A=o*o+h*h+l*l,Ae.emitter===this))}}Us.OCCLUSION_TYPE_NONE=0,Us.OCCLUSION_TYPE_OPTIMISTIC=1,Us.OCCLUSION_TYPE_STRICT=2,Us.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Us.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Us.CULLINGSTRATEGY_STANDARD=0,Us.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Us.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Us.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,d("BABYLON.AbstractMesh",Us);class ks{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){he.Clone((()=>e),this)}serialize(){return he.Serialize(this)}parse(e,t,i){he.Parse((()=>this),e,t,i)}}var Vs,Gs,zs;z([q()],ks.prototype,"func",null),z([q()],ks.prototype,"funcRef",null),z([q()],ks.prototype,"funcMask",null),z([q()],ks.prototype,"opStencilFail",null),z([q()],ks.prototype,"opDepthFail",null),z([q()],ks.prototype,"opStencilDepthPass",null),z([q()],ks.prototype,"mask",null),z([q()],ks.prototype,"enabled",null),(zs=Vs||(Vs={}))[zs.Created=1]="Created",zs[zs.Disposed=2]="Disposed",zs[zs.GetDefineNames=4]="GetDefineNames",zs[zs.PrepareUniformBuffer=8]="PrepareUniformBuffer",zs[zs.IsReadyForSubMesh=16]="IsReadyForSubMesh",zs[zs.PrepareDefines=32]="PrepareDefines",zs[zs.BindForSubMesh=64]="BindForSubMesh",zs[zs.PrepareEffect=128]="PrepareEffect",zs[zs.GetAnimatables=256]="GetAnimatables",zs[zs.GetActiveTextures=512]="GetActiveTextures",zs[zs.HasTexture=1024]="HasTexture",zs[zs.FillRenderTargetTextures=2048]="FillRenderTargetTextures",zs[zs.HasRenderTargetTextures=4096]="HasRenderTargetTextures",zs[zs.HardBindForSubMesh=8192]="HardBindForSubMesh";class Ws{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,1!==t&&1!==e||this.markAsDirty(Ws.MiscDirtyFlag+Ws.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Ws.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Ws.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new se.cP),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new se.cP),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new se.cP),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Ws.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(Ws.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Ws.WireFrameFillMode:case Ws.LineListDrawMode:case Ws.LineLoopDrawMode:case Ws.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Ws.WireFrameFillMode:Ws.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Ws.PointFillMode:case Ws.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Ws.PointFillMode:Ws.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Ws.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&k.V.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new se.cP,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new ks,this._useUBO=!1,this._fillMode=Ws.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||_.q.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Xe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new pt(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Ws.ClockWiseSideOrientation:this.sideOrientation=Ws.CounterClockWiseSideOrientation,this._uniformBuffer=new qe(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Ws.OnEventObservable.notifyObservers(this,Vs.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Ws.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Ws.MATERIAL_OPAQUE||this._transparencyMode===Ws.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(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 t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(Ws.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===Ws.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Vs.PrepareUniformBuffer,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,zt(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&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(Vs.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Vs.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Vs.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Ws._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new et(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new Rs(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);r.clipPlane&&(n.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Ws._DirtyCallbackArray.length=0,e&Ws.TextureDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._TextureDirtyCallBack),e&Ws.LightDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._LightsDirtyCallBack),e&Ws.FresnelDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._FresnelDirtyCallBack),e&Ws.AttributesDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._AttributeDirtyCallBack),e&Ws.MiscDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._MiscDirtyCallBack),e&Ws.PrePassDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._PrePassDirtyCallBack),Ws._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Ws._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.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 t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Ws._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Ws._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Ws._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Ws._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Ws._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Ws._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Ws._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Ws._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Ws._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Ws._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==is.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Vs.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=he.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){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return k.V.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=Xe.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let a=t.pluginManager?.getPlugin(n.name);if(!a){const e=Xe.Instantiate("BABYLON."+r);e&&(a=new e(t))}a?.parse(n,i,s)}}}Ws.TriangleFillMode=0,Ws.WireFrameFillMode=1,Ws.PointFillMode=2,Ws.PointListDrawMode=3,Ws.LineListDrawMode=4,Ws.LineLoopDrawMode=5,Ws.LineStripDrawMode=6,Ws.TriangleStripDrawMode=7,Ws.TriangleFanDrawMode=8,Ws.ClockWiseSideOrientation=0,Ws.CounterClockWiseSideOrientation=1,Ws.TextureDirtyFlag=1,Ws.LightDirtyFlag=2,Ws.FresnelDirtyFlag=4,Ws.AttributesDirtyFlag=8,Ws.MiscDirtyFlag=16,Ws.PrePassDirtyFlag=32,Ws.AllDirtyFlag=63,Ws.MATERIAL_OPAQUE=0,Ws.MATERIAL_ALPHATEST=1,Ws.MATERIAL_ALPHABLEND=2,Ws.MATERIAL_ALPHATESTANDBLEND=3,Ws.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Ws.MATERIAL_NORMALBLENDMETHOD_RNM=1,Ws.OnEventObservable=new se.cP,Ws._AllDirtyCallBack=e=>e.markAllAsDirty(),Ws._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Ws._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Ws._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Ws._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Ws._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Ws._LightsDirtyCallBack=e=>e.markAsLightDirty(),Ws._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Ws._FresnelAndMiscDirtyCallBack=e=>{Ws._FresnelDirtyCallBack(e),Ws._MiscDirtyCallBack(e)},Ws._TextureAndMiscDirtyCallBack=e=>{Ws._TextureDirtyCallBack(e),Ws._MiscDirtyCallBack(e)},Ws._DirtyCallbackArray=[],Ws._RunDirtyCallBacks=e=>{for(const t of Ws._DirtyCallbackArray)t(e)},z([q()],Ws.prototype,"id",void 0),z([q()],Ws.prototype,"uniqueId",void 0),z([q()],Ws.prototype,"name",void 0),z([q()],Ws.prototype,"metadata",void 0),z([q()],Ws.prototype,"checkReadyOnEveryCall",void 0),z([q()],Ws.prototype,"checkReadyOnlyOnce",void 0),z([q()],Ws.prototype,"state",void 0),z([q("alpha")],Ws.prototype,"_alpha",void 0),z([q("backFaceCulling")],Ws.prototype,"_backFaceCulling",void 0),z([q("cullBackFaces")],Ws.prototype,"_cullBackFaces",void 0),z([q()],Ws.prototype,"sideOrientation",void 0),z([q("alphaMode")],Ws.prototype,"_alphaMode",void 0),z([q()],Ws.prototype,"_needDepthPrePass",void 0),z([q()],Ws.prototype,"disableDepthWrite",void 0),z([q()],Ws.prototype,"disableColorWrite",void 0),z([q()],Ws.prototype,"forceDepthWrite",void 0),z([q()],Ws.prototype,"depthFunction",void 0),z([q()],Ws.prototype,"separateCullingPass",void 0),z([q("fogEnabled")],Ws.prototype,"_fogEnabled",void 0),z([q()],Ws.prototype,"pointSize",void 0),z([q()],Ws.prototype,"zOffset",void 0),z([q()],Ws.prototype,"zOffsetUnits",void 0),z([q()],Ws.prototype,"pointsCloud",null),z([q()],Ws.prototype,"fillMode",null),z([q()],Ws.prototype,"useLogarithmicDepth",null),z([q()],Ws.prototype,"transparencyMode",null);class Xs extends Ws{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=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);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){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Xs(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,ae&&ae.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}d("BABYLON.MultiMaterial",Xs);class Hs{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Ks{constructor(){this.visibleInstances={},this.batchCache=new Ys,this.batchCacheReplacementModeInFrozenMode=new Ys,this.instancesBufferSize=2048}}class Ys{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class qs{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class js{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 Zs extends Us{static _GetDefaultSideOrientation(e){return e||Zs.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(G.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(G.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new se.cP),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new se.cP),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new se.cP),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new se.cP),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new se.cP),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new js,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new Ks,this._thinInstanceDataStorage=new qs,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Zs.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),fe.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,ae&&ae.HasTags(s)&&ae.AddTagsTo(this,ae.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new se.cP(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||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 e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.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 k.V.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Hs(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;ia*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const a=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new Rs(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)Rs.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new Ps;s.set(t,e);const r=this.getScene();new Ds(Ds.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Ds.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(G.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(G.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(G.NormalKind);if(!t)return this;Ps.ComputeNormals(i,e,t),this.updateVerticesData(G.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(Ds.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new Ds(Ds.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Ps;t.indices=e;const s=this.getScene();new Ds(Ds.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case Ws.PointFillMode:n=null;break;case Ws.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Ws.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==Ws.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ws.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),a=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&a&&(n.visibleInstances[e]=t[a])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],a=n?n.length:0,o=this._instanceDataStorage,h=o.instancesBufferSize;let l=o.instancesBuffer,c=o.instancesPreviousBuffer;const d=16*(a+1)*4;for(;o.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const a=s.getEngine();let o=0,h=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(o=s.activeCamera.maxZ,h=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const l=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||l.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,d=this._instanceDataStorage,u=e.getMaterial();if(!u)return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this;if(d.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===u){if(u._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!u._storeEffectOnSubMeshes&&!u._getDrawWrapper()._wasPreviouslyReady)return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this}else{if(u._storeEffectOnSubMeshes){if(!u.isReadyForSubMesh(this,e,c))return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this}else if(!u.isReady(this,c))return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=u}let f;t&&a.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),f=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const _=f?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,_);if(!f||!_)return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this;const p=i||this;let g;if(d.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)g=d.sideOrientation;else{const e=p._getWorldMatrixDeterminant();g=this.overrideMaterialSideOrientation,null==g&&(g=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(g=g===Ws.ClockWiseSideOrientation?Ws.CounterClockWiseSideOrientation:Ws.ClockWiseSideOrientation),d.sideOrientation=g}const m=this._internalMeshDataInfo._effectiveMaterial._preBind(f,g);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&a.setDepthWrite(!0);const T=this._internalMeshDataInfo._effectiveMaterial,x=T.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,_,x,!1);const E=p.getWorldMatrix();T._storeEffectOnSubMeshes?T.bindForSubMesh(E,this,e):T.bind(E,this),!T.backFaceCulling&&T.separateCullingPass&&(a.setState(!0,T.zOffset,!1,!m,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._processRendering(this,e,_,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),a.setState(!0,T.zOffset,!1,m,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,_,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,_);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),h&&(h.maxZ=o,s.updateTransformMatrix(!0)),s.performancePriority!==is.Aggressive||d.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(G.MatricesWeightsKind)&&(this.isVerticesDataPresent(G.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(G.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&d++,c+=n,i=n}if(h[d]++,d>n&&(n=d),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&a++}}const l=this.skeleton.bones.length,c=this.getVerticesData(G.MatricesIndicesKind),d=this.getVerticesData(G.MatricesIndicesExtraKind);let u=0;for(let e=0;e=l||i<0)&&u++}return{skinned:!0,valid:0===r&&0===a&&0===u,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+a+"\nWeightCounts = ["+h+"]\nNumber of bones = "+l+"\nBad Bone Indices = "+u}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Xe.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(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(G.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(G.PositionKind);const s=M.Zero();let r;for(r=0;r{const o=e.width,h=e.height,l=this.getEngine().createCanvas(o,h).getContext("2d");l.drawImage(e,0,0);const c=l.getImageData(0,0,o,h).data;this.applyDisplacementMapFromBuffer(c,o,h,t,i,r,n,a),s&&s(this)}),o||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,a,o=!1){if(!this.isVerticesDataPresent(G.PositionKind)||!this.isVerticesDataPresent(G.NormalKind)||!this.isVerticesDataPresent(G.UVKind))return k.V.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(G.PositionKind,!0,!0),l=this.getVerticesData(G.NormalKind),c=this.getVerticesData(G.UVKind);let d=M.Zero();const u=M.Zero(),f=A.Zero();n=n||A.Zero(),a=a||new A(1,1);for(let o=0;o{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,h=o?this.getVerticesData(G.MatricesIndicesExtraKind):null,l=o?this.getVerticesData(G.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),d=M.Zero(),u=new y,f=new y;let _,p=0;for(let e=0;e0&&(y.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[p+_]),g,f),u.addToSelf(f));if(o)for(_=0;_<4;_++)g=l[p+_],g>0&&(y.FromFloat32ArrayToRefScaled(c,Math.floor(16*h[p+_]),g,f),u.addToSelf(f));M.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],u,d),d.toArray(s,e),t&&(M.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],u,d),d.toArray(r,e)),u.reset()}return this.updateVerticesData(G.PositionKind,s),t&&this.updateVerticesData(G.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:M.Zero(),max:M.Zero()}}static Center(e){const t=e instanceof Array?Zs.MinMax(e):e;return M.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return bs(Zs._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return a=Zs._MergeMeshesCoroutine(e,t,i,s,r,n,!0),o=function(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{As(i,s,r)}),0)):As(i,s,r)}}(),new Promise(((e,t)=>{Ms(a,o,e,t,h)}));var a,o,h}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,a){if(0===(e=e.filter(Boolean)).length)return null;let o;if(!i){let t=0;for(o=0;o=65536)return k.V.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const h=new Array,l=new Array,c=new Array,d=e[0].overrideMaterialSideOrientation;for(o=0;o{const t=e.computeWorldMatrix(!0);return{vertexData:Ps.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:_,transform:p}=f(u);a&&(yield);const g=new Array(e.length-1);for(let t=1;t{throw(0,re.n)("GroundMesh")},Zs._GoldbergMeshParser=(e,t)=>{throw(0,re.n)("GoldbergMesh")},Zs._LinesMeshParser=(e,t)=>{throw(0,re.n)("LinesMesh")},Zs._GreasedLineMeshParser=(e,t)=>{throw(0,re.n)("GreasedLineMesh")},Zs._GreasedLineRibbonMeshParser=(e,t)=>{throw(0,re.n)("GreasedLineRibbonMesh")},Zs._TrailMeshParser=(e,t)=>{throw(0,re.n)("TrailMesh")},d("BABYLON.Mesh",Zs);class Qs{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new se.cP,this._onDataLayoutChanged=new se.cP,this._animationPropertiesOverride=null,this._scene=i||_.q.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=he.Clone((()=>new Qs(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),he.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Qs(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t{const i=f.width,n=a(e);if(n){if(o){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const a=this._getRGBABufferInternalSizedFormat(r);let h=!1;t===u.RGB&&(t=u.RGBA,h=!0),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const l=o(n);for(let s=0;s>s;for(let i=0;i<6;i++){let o=l[s][i];h&&(o=$s(o,n,n,r)),u.texImage2D(i,s,a,n,n,0,t,e,o)}}this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,n,s,r,d);f.isReady=!0,t?.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),h&&h()}};return this._loadFile(e,(e=>{_(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(f),l&&e&&l(e.status+" "+e.statusText,i)})),f},Ke.w.prototype.createRawTexture2DArray=Js(!1),Ke.w.prototype.createRawTexture3D=Js(!0),Ke.w.prototype.updateRawTexture2DArray=er(!1),Ke.w.prototype.updateRawTexture3D=er(!0);class tr extends st{get depth(){return this._depth}constructor(e,t,i,s,r,n,a=!0,o=!1,h=st.TRILINEAR_SAMPLINGMODE,l=0,c){super(null,n,!a,o),this.format=r,this._texture=n.getEngine().createRawTexture2DArray(e,t,i,s,r,a,o,h,null,l,c),this._depth=s,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,s,r,n=!0,a=!1,o=3,h=0){return new tr(e,t,i,s,5,r,n,a,o,h)}}class ir{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new nt(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=_.q.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return ir.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new ir(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=ir.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void k.V.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new ir(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(Qs.Parse(s,t));return i}}ir.EnableTextureStorage=!0,ir.MaxActiveMorphTargetsInVertexAttributeMode=8,Zs._instancedMeshFactory=(e,t)=>{const i=new sr(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class sr extends Us{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 e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.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){this._sourceMesh?.receiveShadows!==e&&Xe.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Xe.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Xe.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Xe.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&&k.V.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||k.V.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!==ws.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new y);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,R.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(R.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&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;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 ar extends mi{constructor(e){super(),this._wasAddedToScene=!1,(e=e||_.q.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof sr){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(k.V.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>k.V.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Us&&-1!==this.meshes.indexOf(e)||e instanceof ws&&-1!==this.transformNodes.indexOf(e)||e instanceof Ze&&-1!==this.lights.indexOf(e)||e instanceof ni&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Xe.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new nr,a=[],o=[],h={doNotInstantiate:!0,...i},l=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(l,c,e,h.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(l,c,e,h.predicate);const d=this._topologicalSort(l),u=(i,a)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Zs){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===a.parent&&n.rootNodes.push(a)};return d.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],a=("number"==typeof n?r[n]:i).createInstance(t.name);u(t,a)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:h.doNotInstantiate&&(t="function"==typeof h.doNotInstantiate?!h.doNotInstantiate(e):!h.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);u(e,i)}})),this.skeletons.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==a.indexOf(i))continue;a.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Xe.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((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Xe.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 e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new rr);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Zs("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=_.q.LastCreatedScene,t,i=null){if(!e)return k.V.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof Zs?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof ws?this.transformNodes.push(e):e instanceof Ze?this.lights.push(e):e instanceof ni&&this.cameras.push(e),e instanceof Us){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class or extends ce{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,a=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??y.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new y,this._absoluteBindMatrix=new y,this._absoluteInverseBindMatrix=new y,this._finalMatrix=new y,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=R.Vector3[0],t=R.Quaternion[0],i=R.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??S.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=M.Zero(),this._localRotation=S.Zero(),this._localPosition=M.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,y.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e=0?n.referenceFrame:0;let h=0;const l=a._keys[0];let c=a._keys.length-1;const d=a._keys[c],u={referenceValue:l.value,referencePosition:R.Vector3[0],referenceQuaternion:R.Quaternion[0],referenceScaling:R.Vector3[1],keyPosition:R.Vector3[2],keyQuaternion:R.Quaternion[1],keyScaling:R.Vector3[3]};let f=l.frame,_=d.frame;if(n.range){const e=a.getRange(n.range);e&&(f=e.from,_=e.to)}else f=n.fromFrame??f,_=n.toFrame??_;if(f!==l.frame&&(h=a.createKeyForFrame(f)),_!==d.frame&&(c=a.createKeyForFrame(_)),1===a._keys.length){const e=a._getKeyValue(a._keys[0]);u.referenceValue=e.clone?e.clone():e}else if(o<=l.frame){const e=a._getKeyValue(l.value);u.referenceValue=e.clone?e.clone():e}else if(o>=d.frame){const e=a._getKeyValue(d.value);u.referenceValue=e.clone?e.clone():e}else{gr.key=0;const e=a._interpolate(o,gr);u.referenceValue=e.clone?e.clone():e}a.dataType===mr.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():a.dataType===mr.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace());let p=Number.MAX_VALUE;const g=n.clipKeys?[]:null;for(let e=h;e<=c;e++){let t=a._keys[e];if((g||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},g&&(p===Number.MAX_VALUE&&(p=t.frame),t.frame-=p,g.push(t))),!e||a.dataType===mr.ANIMATIONTYPE_FLOAT||t.value!==l.value)switch(a.dataType){case mr.ANIMATIONTYPE_MATRIX:t.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),y.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,t.value);break;case mr.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(t.value,t.value);break;case mr.ANIMATIONTYPE_VECTOR2:case mr.ANIMATIONTYPE_VECTOR3:case mr.ANIMATIONTYPE_COLOR3:case mr.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(u.referenceValue,t.value);break;case mr.ANIMATIONTYPE_SIZE:t.value.width-=u.referenceValue.width,t.value.height-=u.referenceValue.height;break;default:t.value-=u.referenceValue}}return g&&a.setKeys(g,!0),a}static TransitionTo(e,t,i,s,r,n,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;const h=r*(a/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const l=s.beginAnimation(i,0,h,!1);return l.onAnimationEnd=o,l}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?mr.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=mr._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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const a=s[n],o=s[n+1];if(i&&(e===a.frame||e===o.frame))return;const h=this._getKeyValue(a.value),l=this._getKeyValue(o.value);if(a.interpolation===Gs.STEP)return o.frame>e?h:l;const c=void 0!==a.outTangent&&void 0!==o.inTangent,d=o.frame-a.frame;let u=(e-a.frame)/d;const f=a.easingFunction||this.getEasingFunction();switch(null!==f&&(u=f.ease(u)),this.dataType){case mr.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(h,a.outTangent*d,l,o.inTangent*d,u):this.floatInterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case mr.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.quaternionInterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||cr).scale(t.repeatCount))}return e}case mr.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.vector3InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||dr).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.vector2InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||ur).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_SIZE:switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,l,u);case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,l,u).add((t.offsetValue||fr).scale(t.repeatCount))}break;case mr.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.color3InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||_r).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.color4InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||pr).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return mr.AllowMatricesInterpolation?this.matrixInterpolateFunction(h,l,u,t.workValue):h;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}}return 0}matrixInterpolateFunction(e,t,i,s){return mr.AllowMatrixDecomposeForInterpolation?s?(y.DecomposeLerpToRef(e,t,i,s),s):y.DecomposeLerp(e,t,i):s?(y.LerpToRef(e,t,i,s),s):y.Lerp(e,t,i)}clone(){const e=new mr(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){gr.key=0;const t=this._interpolate(e,gr,!0);if(!t)return this._keys[gr.key].frame===e?gr.key:gr.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(gr.key+1,0,i),gr.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&&(a=t.values[1]),t.values.length>=3&&(o=t.values[2]),t.values.length>=4&&(h=t.values[3]);break;case mr.ANIMATIONTYPE_QUATERNION:if(r=S.FromArray(t.values),t.values.length>=8){const e=S.FromArray(t.values.slice(4,8));e.equals(S.Zero())||(a=e)}if(t.values.length>=12){const e=S.FromArray(t.values.slice(8,12));e.equals(S.Zero())||(o=e)}t.values.length>=13&&(h=t.values[12]);break;case mr.ANIMATIONTYPE_MATRIX:r=y.FromArray(t.values),t.values.length>=17&&(h=t.values[16]);break;case mr.ANIMATIONTYPE_COLOR3:r=L.FromArray(t.values),t.values[3]&&(a=L.FromArray(t.values[3])),t.values[4]&&(o=L.FromArray(t.values[4])),t.values[5]&&(h=t.values[5]);break;case mr.ANIMATIONTYPE_COLOR4:r=N.FromArray(t.values),t.values[4]&&(a=N.FromArray(t.values[4])),t.values[5]&&(o=N.FromArray(t.values[5])),t.values[6]&&(h=N.FromArray(t.values[6]));break;case mr.ANIMATIONTYPE_VECTOR3:default:r=M.FromArray(t.values),t.values[3]&&(a=M.FromArray(t.values[3])),t.values[4]&&(o=M.FromArray(t.values[4])),t.values[5]&&(h=t.values[5])}const l={};l.frame=t.frame,l.value=r,null!=a&&(l.inTangent=a),null!=o&&(l.outTangent=o),null!=h&&(l.interpolation=h),s.push(l)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new pe;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new pe;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}mr._UniqueIdGenerator=0,mr.AllowMatricesInterpolation=!1,mr.AllowMatrixDecomposeForInterpolation=!0,mr.SnippetUrl="https://snippet.babylonjs.com",mr.ANIMATIONTYPE_FLOAT=0,mr.ANIMATIONTYPE_VECTOR3=1,mr.ANIMATIONTYPE_QUATERNION=2,mr.ANIMATIONTYPE_MATRIX=3,mr.ANIMATIONTYPE_COLOR3=4,mr.ANIMATIONTYPE_COLOR4=7,mr.ANIMATIONTYPE_VECTOR2=5,mr.ANIMATIONTYPE_SIZE=6,mr.ANIMATIONLOOPMODE_RELATIVE=0,mr.ANIMATIONLOOPMODE_CYCLE=1,mr.ANIMATIONLOOPMODE_CONSTANT=2,mr.ANIMATIONLOOPMODE_YOYO=4,mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,mr.CreateFromSnippetAsync=mr.ParseFromSnippetAsync,d("BABYLON.Animation",mr),ce._AnimationRangeFactory=(e,t,i)=>new lr(e,t,i);class Tr{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=y.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new se.cP,this.bones=[],this._scene=i||_.q.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,R.Matrix[1]),e._updateAbsoluteBindMatrices(R.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=hr.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=hr.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new Tr(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=M.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const a=t.rest?y.FromArray(t.rest):null,o=new or(t.name,i,n,y.FromArray(t.matrix),a,null,r);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(mr.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class xr{static Data=["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACMElEQVRYR+2Xv4pTQRTGf2dubhLdICiii2KnYKHVolhauKWPoGAnNr6BD6CvIVaihYuI2i1ia0BY0MZGRHQXjZj/mSPnnskfNWiWZUlzJ5k7M2cm833nO5Mziej2DWWJRUoCpQKlAntSQCqgw39/iUWAGmh37jrRnVsKlgpiqmkoGVABA7E57fvY+pJDdgKqF6HzFCSADkDq+F6AHABtQ+UMVE5D7zXod7fFNhTEckTbj5XQgHzNN+5tQvc5NG7C6BNkp6D3EmpXHDR+dQAjFLchW3VS9rlw3JBh+B7ys5Cf9z0GW1C/7P32AyBAOAz1q4jGliIH3YPuBnSfQX4OGreTIgEYQb/pBDtPnEQ4CivXYPAWBk13oHrB54yA9QuSn2H4AcKRpEILDt0BUzj+RLR1V5EqjD66NPRBVpLcQwjHoHYJOhsQv6U4mnzmrIXJCFr4LDwm/xBUoboG9XX4cc9VKdYoSA2yk5NQLJaKDUjTBoveG3Z2TElTxwjNK4M3LEZgUdDdruvcXzKBpStgp2NPiWi3ks9ZXxIoFVi+AvHLdc9TqtjL3/aYjpPlrzOcEnK62Szhimdd7xX232zFDTgtxezOu3WNMRLjiKgjtOhHVMd1loynVHvOgjuIIJMaELEqhJAV/RCSLbWTcfPFakFgFlALTRRvx+ok6Hlp/Q+v3fmx90bMyUzaEAhmM3KvHlXTL5DxnbGf/1M8RNNACLL5MNtPxP/mypJAqcDSFfgFhpYqWUzhTEAAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII="]}function Er(e){const t=(e=e.replace(/\\/g,"/")).split("/"),i=[];for(let e=0;e{this._createTexture(t,i,e,s,n,a,((e,t)=>{o?.(e,t)}))}),void 0,!0,!0,((e,t)=>{o?.(e?e.status+" "+e.statusText:"",t)}))}loadFromArrayBuffer(e){this._createTexture(this._scene,this._assetContainer,this.cacheKey,e,this._options,this._onLoad,((e,t)=>{this._onError?.(e,t)}))}_onDisposeCallback=null;registerOnDisposeCallback(e){this._onDisposeCallback=e,this._texture.onDisposeObservable.addOnce(e)}unregisterOnDisposeCallback(){const e=this._onDisposeCallback;return null===e?null:(this._onDisposeCallback=null,this._texture.onDisposeObservable.removeCallback(e),e)}_createTexture(e,t,i,s,r,n,a){e._blockEntityCollection=!!t;const o={noMipmap:r.noMipmap,invertY:r.invertY,samplingMode:r.samplingMode,onLoad:()=>{null===this._texture?null!==n&&Me.SetImmediate(n):n?.()},onError:a,buffer:s,deleteBuffer:r.deleteBuffer,format:r.format,mimeType:r.mimeType},h=this._texture=new st("data:"+i,e,o);h._parentContainer=t,e._blockEntityCollection=!1,t?.textures.push(h),h.name=i}get texture(){return this._texture}}class br{onModelTextureLoadedObservable=new Map;textureCache=new Map;_textureLoadInfoMap=new Map;_loadingModels=new Map;_errorTexturesReferenceCount=new Map;_incrementLeftLoadCount(e){let t=this._loadingModels.get(e);void 0===t&&(t=new vr(e),this._loadingModels.set(e,t)),t.leftLoadCount+=1;let i=this.onModelTextureLoadedObservable.get(e);return void 0===i&&(i=new se.cP,this.onModelTextureLoadedObservable.set(e,i)),t}_decrementLeftLoadCount(e){if(e.leftLoadCount-=1,!e.isRequesting&&0===e.leftLoadCount){this._removeErrorTexturesReferenceCount(e.uniqueId),this._loadingModels.delete(e.uniqueId);const t=this.onModelTextureLoadedObservable.get(e.uniqueId);t?.notifyObservers(),t?.clear(),this.onModelTextureLoadedObservable.delete(e.uniqueId)}}loadModelTexturesEnd(e){const t=this._loadingModels.get(e);if(void 0!==t&&(t.isRequesting=!1,0===t.leftLoadCount)){this._removeErrorTexturesReferenceCount(e),this._loadingModels.delete(e);const t=this.onModelTextureLoadedObservable.get(e);t?.notifyObservers(),t?.clear(),this.onModelTextureLoadedObservable.delete(e)}}_addErrorTextureReferenceCount(e,t){this._loadingModels.get(e).errorTextureDatas.push(t),this._errorTexturesReferenceCount.set(t,(this._errorTexturesReferenceCount.get(t)??0)+1)}_removeErrorTexturesReferenceCount(e){const t=this._loadingModels.get(e);for(let e=0;e{this._textureLoadInfoMap.delete(e.cacheKey),this.textureCache.delete(e.cacheKey),this._errorTexturesReferenceCount.delete(e)}))}_createTextureCacheKey(e,t){const i=e.lastIndexOf(".");let s="";return-1!==i&&(s=e.substring(i),e=e.substring(0,i)),e+ +(t.noMipmap??!1)+ +(t.invertY??!0)+(t.samplingMode??st.TRILINEAR_SAMPLINGMODE)+(t.format??Mi.TEXTUREFORMAT_RGBA)+s}async _loadTextureAsyncInternal(e,t,i,s,r,n,a){const o=this._incrementLeftLoadCount(e),h=this._createTextureCacheKey(t,a);let l=this._textureLoadInfoMap.get(h);void 0===l&&(l=new Ar,this._textureLoadInfoMap.set(h,l));let c=this.textureCache.get(h);if(void 0===c&&!l.hasLoadError){const o=null!==s?xr.Data[s]:t;c=new Mr(h,r,n,o,null!==i,a,(()=>{this._handleTextureOnDispose(c),l.hasLoadError=!1,l.observable.notifyObservers(!1),l.observable.clear()}),((t,i)=>{null!==c.texture&&this._handleTextureOnDispose(c),this._addErrorTextureReferenceCount(e,c),l.hasLoadError=!0,l.observable.notifyObservers(!0),l.observable.clear()})),this.textureCache.set(h,c);const d=i instanceof Blob?await i.arrayBuffer():i;null!==d&&c.loadFromArrayBuffer(d)}return null!==c.texture&&c.texture.isReady()?(this._decrementLeftLoadCount(o),l.hasLoadError?null:c.texture):new Promise((e=>{l.observable.addOnce((t=>{this._decrementLeftLoadCount(o),e(t?null:c.texture)}))}))}async loadTextureAsync(e,t,i,s,r,n){let a;"number"==typeof i?((i<-1||9this._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[Pr._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.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(((e,t)=>e.priority-t.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&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case Vs.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.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)=>{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 r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let a=s.getCustomCode(i)?.[t];if(a){if(s.resolveIncludes){if(null===n){const t=yt.w.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:gt.l.GetShadersRepository(t),includesShadersStore:gt.l.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,(0,Ae.Iq)(a,n,(e=>a=e))}r+=a+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=Cr.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let a=n.exec(i);for(;null!==a;){let e=r;for(let t=0;t{Dr.length=0,Or=!1,Ws.OnEventObservable.remove(Fr),Fr=null}));const Dr=[];let Or=!1,Fr=null;class wr{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new Pr(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){he.Clone((()=>e),this)}serialize(){return he.Serialize(this)}parse(e,t,i){he.Parse((()=>this),e,t,i)}}z([q()],wr.prototype,"name",void 0),z([q()],wr.prototype,"priority",void 0),z([q()],wr.prototype,"resolveIncludes",void 0),z([q()],wr.prototype,"registerForExtraEvents",void 0),d("BABYLON.MaterialPluginBase",wr);class Lr extends yr{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Nr extends wr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new Lr,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ws.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&&Rr.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&Rr.DetailTextureEnabled&&this._isEnabled?(Wt(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&&Rr.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Xt(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Rr.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){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}z([j("detailTexture"),Y("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"texture",void 0),z([q()],Nr.prototype,"diffuseBlendLevel",void 0),z([q()],Nr.prototype,"roughnessBlendLevel",void 0),z([q()],Nr.prototype,"bumpLevel",void 0),z([q(),Y("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"normalBlendMethod",void 0),z([q(),Y("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"isEnabled",void 0);const Br={effect:null,subMesh:null};class Ur extends yr{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class kr extends Ir{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new L(0,0,0),this.diffuseColor=new L(1,1,1),this.specularColor=new L(1,1,1),this.emissiveColor=new L(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new nt(16),this._worldViewProjectionMatrix=y.Zero(),this._globalAmbientColor=new L(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Nr(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Sr,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),kr.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),kr.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!!(kr.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(kr.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Ws.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ws.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}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(Vs.GetDefineNames,this._eventInfo),t.materialDefines=new Ur(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=r.getEngine();n._needNormals=function(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0;const o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(qt(e,t,n,a,i,s,o),a++,a===r)break;i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}(r,n);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(function(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===st.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case st.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case st.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case st.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case st.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case st.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case st.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case st.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case st.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case st.CUBIC_MODE:case st.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&kr.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;Wt(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&kr.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;Wt(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&kr.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;Wt(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&kr.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;Wt(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&kr.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(kr.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),function(e,t,i,s,r,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=s,a.FOG=r&&function(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),function(e,t,i,s,r,n=null,a=!1){let o=function(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=1===e.activeCamera.mode?1:0,a=0===e.activeCamera.mode?1:0;(s^n||r^a)&&(t.CAMERA_ORTHOGRAPHIC=1===n,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}(e,s);!1!==n&&(o=function(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),a=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),h=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==a&&(i.CLIPPLANE3=a,s=!0),i.CLIPPLANE4!==o&&(i.CLIPPLANE4=o,s=!0),i.CLIPPLANE5!==h&&(i.CLIPPLANE5=h,s=!0),i.CLIPPLANE6!==l&&(i.CLIPPLANE6=l,s=!0),s}(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,o=!0),s.INSTANCES!==r&&(s.INSTANCES=r,o=!0),s.THIN_INSTANCES!==a&&(s.THIN_INSTANCES=a,o=!0),o&&s.markAsUnprocessed()}(r,a,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),function(e,t,i,s,r=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&function(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}(e,t),r&&function(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}(e,t),a&&function(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}(e,t)}(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let h=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new Ct;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),function(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));r++}(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const o=[G.PositionKind];n.NORMAL&&o.push(G.NormalKind),n.TANGENT&&o.push(G.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&o.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&o.push(G.ColorKind),function(e,t,i,s){i.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}(o,e,n,s),function(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Vt(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}(o,n),kt(o,e,n),Ht(o,0,n);let l="default";const c=["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"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],u=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=o,this._eventInfo.samplers=d,this._eventInfo.uniformBuffersNames=u,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(Vs.PrepareEffect,this._eventInfo),Sr.AddUniforms(c),Sr.AddSamplers(d),Ii&&(Ii.PrepareUniforms(c,n),Ii.PrepareSamplers(d,n)),function(e,t,i,s=4){let r,n=null;if(e.uniformsNames){const a=e;r=a.uniformsNames,n=a.uniformBuffersNames,t=a.samplers,i=a.defines,s=a.maxSimultaneousLights||0}else r=e,t||(t=[]);for(let e=0;e0&&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){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=he.Clone((()=>new kr(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=he.Parse((()=>new kr(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Ws._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return Rr.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Rr.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Rr.DetailTextureEnabled}static set DetailTextureEnabled(e){Rr.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Rr.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Rr.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Rr.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Rr.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Rr.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Rr.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Rr.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Rr.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Rr.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Rr.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Rr.BumpTextureEnabled}static set BumpTextureEnabled(e){Rr.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Rr.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Rr.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Rr.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Rr.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Rr.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Rr.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Rr.FresnelEnabled}static set FresnelEnabled(e){Rr.FresnelEnabled=e}}z([j("diffuseTexture")],kr.prototype,"_diffuseTexture",void 0),z([Y("_markAllSubMeshesAsTexturesAndMiscDirty")],kr.prototype,"diffuseTexture",void 0),z([j("ambientTexture")],kr.prototype,"_ambientTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"ambientTexture",void 0),z([j("opacityTexture")],kr.prototype,"_opacityTexture",void 0),z([Y("_markAllSubMeshesAsTexturesAndMiscDirty")],kr.prototype,"opacityTexture",void 0),z([j("reflectionTexture")],kr.prototype,"_reflectionTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"reflectionTexture",void 0),z([j("emissiveTexture")],kr.prototype,"_emissiveTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"emissiveTexture",void 0),z([j("specularTexture")],kr.prototype,"_specularTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"specularTexture",void 0),z([j("bumpTexture")],kr.prototype,"_bumpTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"bumpTexture",void 0),z([j("lightmapTexture")],kr.prototype,"_lightmapTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"lightmapTexture",void 0),z([j("refractionTexture")],kr.prototype,"_refractionTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"refractionTexture",void 0),z([Z("ambient")],kr.prototype,"ambientColor",void 0),z([Z("diffuse")],kr.prototype,"diffuseColor",void 0),z([Z("specular")],kr.prototype,"specularColor",void 0),z([Z("emissive")],kr.prototype,"emissiveColor",void 0),z([q()],kr.prototype,"specularPower",void 0),z([q("useAlphaFromDiffuseTexture")],kr.prototype,"_useAlphaFromDiffuseTexture",void 0),z([Y("_markAllSubMeshesAsTexturesAndMiscDirty")],kr.prototype,"useAlphaFromDiffuseTexture",void 0),z([q("useEmissiveAsIllumination")],kr.prototype,"_useEmissiveAsIllumination",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useEmissiveAsIllumination",void 0),z([q("linkEmissiveWithDiffuse")],kr.prototype,"_linkEmissiveWithDiffuse",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"linkEmissiveWithDiffuse",void 0),z([q("useSpecularOverAlpha")],kr.prototype,"_useSpecularOverAlpha",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useSpecularOverAlpha",void 0),z([q("useReflectionOverAlpha")],kr.prototype,"_useReflectionOverAlpha",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useReflectionOverAlpha",void 0),z([q("disableLighting")],kr.prototype,"_disableLighting",void 0),z([Y("_markAllSubMeshesAsLightsDirty")],kr.prototype,"disableLighting",void 0),z([q("useObjectSpaceNormalMap")],kr.prototype,"_useObjectSpaceNormalMap",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useObjectSpaceNormalMap",void 0),z([q("useParallax")],kr.prototype,"_useParallax",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useParallax",void 0),z([q("useParallaxOcclusion")],kr.prototype,"_useParallaxOcclusion",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useParallaxOcclusion",void 0),z([q()],kr.prototype,"parallaxScaleBias",void 0),z([q("roughness")],kr.prototype,"_roughness",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"roughness",void 0),z([q()],kr.prototype,"indexOfRefraction",void 0),z([q()],kr.prototype,"invertRefractionY",void 0),z([q()],kr.prototype,"alphaCutOff",void 0),z([q("useLightmapAsShadowmap")],kr.prototype,"_useLightmapAsShadowmap",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useLightmapAsShadowmap",void 0),z([Q("diffuseFresnelParameters")],kr.prototype,"_diffuseFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"diffuseFresnelParameters",void 0),z([Q("opacityFresnelParameters")],kr.prototype,"_opacityFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelAndMiscDirty")],kr.prototype,"opacityFresnelParameters",void 0),z([Q("reflectionFresnelParameters")],kr.prototype,"_reflectionFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"reflectionFresnelParameters",void 0),z([Q("refractionFresnelParameters")],kr.prototype,"_refractionFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"refractionFresnelParameters",void 0),z([Q("emissiveFresnelParameters")],kr.prototype,"_emissiveFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"emissiveFresnelParameters",void 0),z([q("useReflectionFresnelFromSpecular")],kr.prototype,"_useReflectionFresnelFromSpecular",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"useReflectionFresnelFromSpecular",void 0),z([q("useGlossinessFromSpecularMapAlpha")],kr.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useGlossinessFromSpecularMapAlpha",void 0),z([q("maxSimultaneousLights")],kr.prototype,"_maxSimultaneousLights",void 0),z([Y("_markAllSubMeshesAsLightsDirty")],kr.prototype,"maxSimultaneousLights",void 0),z([q("invertNormalMapX")],kr.prototype,"_invertNormalMapX",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"invertNormalMapX",void 0),z([q("invertNormalMapY")],kr.prototype,"_invertNormalMapY",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"invertNormalMapY",void 0),z([q("twoSidedLighting")],kr.prototype,"_twoSidedLighting",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"twoSidedLighting",void 0),z([q("applyDecalMapAfterDetailMap")],kr.prototype,"_applyDecalMapAfterDetailMap",void 0),z([Y("_markAllSubMeshesAsMiscDirty")],kr.prototype,"applyDecalMapAfterDetailMap",void 0),d("BABYLON.StandardMaterial",kr),as.DefaultMaterialFactory=e=>new kr("default material",e);class Vr extends yr{SPHERE_TEXTURE=!1;SPHERE_TEXTURE_BLEND_MODE_MULTIPLY=!1;SPHERE_TEXTURE_BLEND_MODE_ADD=!1;TOON_TEXTURE=!1;IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED=!1;APPLY_AMBIENT_COLOR_TO_DIFFUSE=!1;TEXTURE_COLOR=!1;SPHERE_TEXTURE_COLOR=!1;TOON_TEXTURE_COLOR=!1;SDEF=!1}var Gr;!function(e){e[e.Multiply=1]="Multiply",e[e.Add=2]="Add",e[e.SubTexture=3]="SubTexture"}(Gr||(Gr={}));class zr extends wr{_sphereTexture=null;_sphereTextureBlendMode=Gr.Add;_toonTexture=null;_ignoreDiffuseWhenToonTextureIsNull=!1;textureMultiplicativeColor=new N(1,1,1,1);textureAdditiveColor=new N(0,0,0,0);sphereTextureMultiplicativeColor=new N(1,1,1,1);sphereTextureAdditiveColor=new N(0,0,0,0);toonTextureMultiplicativeColor=new N(1,1,1,1);toonTextureAdditiveColor=new N(0,0,0,0);_applyAmbientColorToDiffuse=!0;_useTextureColor=!1;_useSphereTextureColor=!1;_useToonTextureColor=!1;_isEnabled=!1;get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this.markAllDefinesAsDirty(),this._enable(e))}get sphereTexture(){return this._sphereTexture}set sphereTexture(e){this._sphereTexture!==e&&(this._sphereTexture=e,this.markAllSubMeshesAsTexturesDirty())}get sphereTextureBlendMode(){return this._sphereTextureBlendMode}set sphereTextureBlendMode(e){this._sphereTextureBlendMode!==e&&(this._sphereTextureBlendMode=e,this.markAllDefinesAsDirty())}get toonTexture(){return this._toonTexture}set toonTexture(e){this._toonTexture!==e&&(this._toonTexture=e,this.markAllSubMeshesAsTexturesDirty())}get ignoreDiffuseWhenToonTextureIsNull(){return this._ignoreDiffuseWhenToonTextureIsNull}set ignoreDiffuseWhenToonTextureIsNull(e){this._ignoreDiffuseWhenToonTextureIsNull!==e&&(this._ignoreDiffuseWhenToonTextureIsNull=e,this.markAllDefinesAsDirty())}get applyAmbientColorToDiffuse(){return this._applyAmbientColorToDiffuse}set applyAmbientColorToDiffuse(e){this._applyAmbientColorToDiffuse!==e&&(this._applyAmbientColorToDiffuse=e,this.markAllDefinesAsDirty())}get useTextureColor(){return this._useTextureColor}set useTextureColor(e){this._useTextureColor!==e&&(this._useTextureColor=e,this.markAllDefinesAsDirty())}get useSphereTextureColor(){return this._useSphereTextureColor}set useSphereTextureColor(e){this._useSphereTextureColor!==e&&(this._useSphereTextureColor=e,this.markAllDefinesAsDirty())}get useToonTextureColor(){return this._useToonTextureColor}set useToonTextureColor(e){this._useToonTextureColor!==e&&(this._useToonTextureColor=e,this.markAllDefinesAsDirty())}_internalMarkAllSubMeshesAsTexturesDirty;markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"MmdMaterial",100,new Vr,t),this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Mi.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._sphereTexture&&!this._sphereTexture.isReadyOrNotBlocking())}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||(r.DIFFUSE&&r.TEXTURE_COLOR&&(e.updateDirectColor4("textureMultiplicativeColor",this.textureMultiplicativeColor),e.updateDirectColor4("textureAdditiveColor",this.textureAdditiveColor)),r.NORMAL&&r.SPHERE_TEXTURE&&r.SPHERE_TEXTURE_COLOR&&(e.updateDirectColor4("sphereTextureMultiplicativeColor",this.sphereTextureMultiplicativeColor),e.updateDirectColor4("sphereTextureAdditiveColor",this.sphereTextureAdditiveColor)),r.TOON_TEXTURE&&r.TOON_TEXTURE_COLOR&&(e.updateDirectColor4("toonTextureMultiplicativeColor",this.toonTextureMultiplicativeColor),e.updateDirectColor4("toonTextureAdditiveColor",this.toonTextureAdditiveColor)),r.SPHERE_TEXTURE&&null!==s.effect&&this._material.bindView(s.effect)),t.texturesEnabled&&(r.NORMAL&&this._sphereTexture&&e.setTexture("sphereSampler",this._sphereTexture),this._toonTexture&&e.setTexture("toonSampler",this._toonTexture))}dispose(e){e&&(this._sphereTexture?.dispose(),this._toonTexture?.dispose())}getCustomCode(e){if("vertex"===e){const e={};return e.CUSTOM_VERTEX_DEFINITIONS=hs,e[`!${this._escapeRegExp("finalWorld=finalWorld*influence;")}`]=`\n${ls}\nfinalWorld=(finalWorld*influence);\n`,e}if("fragment"===e){const e={CUSTOM_FRAGMENT_DEFINITIONS:"\n#if defined(SPHERE_TEXTURE) && defined(NORMAL)\nuniform sampler2D sphereSampler;\n#endif\n#ifdef TOON_TEXTURE\nuniform sampler2D toonSampler;\n#endif\n",CUSTOM_FRAGMENT_MAIN_BEGIN:"\n#ifdef TOON_TEXTURE\nvec3 toonNdl;\n#endif\n"};e[`!${this._escapeRegExp("#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif")}`]="\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#elif defined(NORMAL) && defined(SPHERE_TEXTURE)\nuniform mat4 view;\n#endif\n",e[`!${this._escapeRegExp("vec3 diffuseColor=vDiffuseColor.rgb;")}`]="\n#ifdef APPLY_AMBIENT_COLOR_TO_DIFFUSE\nvec3 diffuseColor=clamp(vDiffuseColor.rgb+vAmbientColor,0.0,1.0);\n#else\nvec3 diffuseColor=(vDiffuseColor.rgb);\n#endif\n",e[`!${this._escapeRegExp("baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);")}`]="\n#if defined(DIFFUSE) && defined(TEXTURE_COLOR)\nbaseColor=texture2D(diffuseSampler,(vDiffuseUV+uvOffset));baseColor.rgb=mix(\nvec3(1.0),\nbaseColor.rgb*textureMultiplicativeColor.rgb,\ntextureMultiplicativeColor.a\n);baseColor.rgb=clamp(\nbaseColor.rgb+(baseColor.rgb-vec3(1.0))*textureAdditiveColor.a,\n0.0,\n1.0\n)+textureAdditiveColor.rgb;\n#else\nbaseColor=texture2D(diffuseSampler,(vDiffuseUV+uvOffset));\n#endif\n",e[`!${this._escapeRegExp("struct lightingInfo\n{")}`]="\nstruct lightingInfo {\n#ifdef TOON_TEXTURE\n#if !defined(NDOTL)\nfloat ndl;\n#endif\nfloat isToon;\n#endif\n",e[`!${this._escapeRegExp("result.diffuse=ndl*diffuseColor*attenuation;")}`]="\n#ifdef TOON_TEXTURE\nresult.diffuse=diffuseColor*attenuation;result.ndl=ndl;result.isToon=1.0;\n#elif defined(IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED) \nresult.diffuse=diffuseColor*attenuation;\n#else\nresult.diffuse=(ndl*diffuseColor*attenuation);\n#endif\n",e[`!${this._escapeRegExp("diffuseBase+=info.diffuse*shadow;")}`]="\n#ifdef TOON_TEXTURE\ntoonNdl=vec3(clamp(info.ndl*shadow,0.02,0.98));toonNdl.r=texture2D(toonSampler,vec2(0.5,toonNdl.r)).r;toonNdl.g=texture2D(toonSampler,vec2(0.5,toonNdl.g)).g;toonNdl.b=texture2D(toonSampler,vec2(0.5,toonNdl.b)).b;\n#ifdef TOON_TEXTURE_COLOR\ntoonNdl=mix(\nvec3(1.0),\ntoonNdl*toonTextureMultiplicativeColor.rgb,\ntoonTextureMultiplicativeColor.a\n);toonNdl=clamp(\ntoonNdl+(toonNdl-vec3(1.0))*toonTextureAdditiveColor.a,\n0.0,\n1.0\n)+toonTextureAdditiveColor.rgb;\n#endif\ndiffuseBase+=mix(info.diffuse*shadow,toonNdl*info.diffuse,info.isToon);\n#elif defined(IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED)\ndiffuseBase+=info.diffuse;\n#else\ndiffuseBase+=(info.diffuse*shadow);\n#endif\n";const t="\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n";return e[`!${this._escapeRegExp(t)}`]=`\n#ifdef APPLY_AMBIENT_COLOR_TO_DIFFUSE\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#else\n${t.replace("diffuseBase","(diffuseBase)")}#endif\n`,e.CUSTOM_FRAGMENT_BEFORE_FOG="\n#if defined(NORMAL) && defined(SPHERE_TEXTURE)\nvec3 viewSpaceNormal=normalize(mat3(view)*vNormalW);vec2 sphereUV=viewSpaceNormal.xy*0.5+0.5;vec4 sphereReflectionColor=texture2D(sphereSampler,sphereUV);\n#ifdef SPHERE_TEXTURE_COLOR\nsphereReflectionColor.rgb=mix(\nvec3(1.0),\nsphereReflectionColor.rgb*sphereTextureMultiplicativeColor.rgb,\nsphereTextureMultiplicativeColor.a\n);sphereReflectionColor.rgb=clamp(\nsphereReflectionColor.rgb+(sphereReflectionColor.rgb-vec3(1.0))*sphereTextureAdditiveColor.a,\n0.0,\n1.0\n)+sphereTextureAdditiveColor.rgb;\n#endif\nsphereReflectionColor.rgb*=diffuseBase;\n#ifdef SPHERE_TEXTURE_BLEND_MODE_MULTIPLY\ncolor*=sphereReflectionColor;\n#elif defined(SPHERE_TEXTURE_BLEND_MODE_ADD)\ncolor=vec4(color.rgb+sphereReflectionColor.rgb,color.a);\n#endif\n#endif\n",e}return null}prepareDefines(e,t,i){if(this._isEnabled){const s=t.texturesEnabled;e.SPHERE_TEXTURE=null!==this._sphereTexture&&s,e.SPHERE_TEXTURE_BLEND_MODE_MULTIPLY=this._sphereTextureBlendMode===Gr.Multiply,e.SPHERE_TEXTURE_BLEND_MODE_ADD=this._sphereTextureBlendMode===Gr.Add,e.TOON_TEXTURE=null!==this._toonTexture&&s,e.IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED=this._ignoreDiffuseWhenToonTextureIsNull,e.APPLY_AMBIENT_COLOR_TO_DIFFUSE=this._applyAmbientColorToDiffuse,e.TEXTURE_COLOR=this._useTextureColor,e.SPHERE_TEXTURE_COLOR=this._useSphereTextureColor,e.TOON_TEXTURE_COLOR=this._useToonTextureColor,e.SDEF=i.useBones&&i.computeBonesUsingShaders&&!!i.skeleton&&i.isVerticesDataPresent(os.MatricesSdefCKind)}else e.SPHERE_TEXTURE=!1,e.SPHERE_TEXTURE_BLEND_MODE_MULTIPLY=!1,e.SPHERE_TEXTURE_BLEND_MODE_ADD=!1,e.TOON_TEXTURE=!1,e.IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED=!1,e.APPLY_AMBIENT_COLOR_TO_DIFFUSE=!1,e.TEXTURE_COLOR=!1,e.SPHERE_TEXTURE_COLOR=!1,e.TOON_TEXTURE_COLOR=!1,e.SDEF=!1}hasTexture(e){return this._sphereTexture===e||this._toonTexture===e}getActiveTextures(e){this._sphereTexture&&e.push(this._sphereTexture),this._toonTexture&&e.push(this._toonTexture)}getAnimatables(e){this._sphereTexture&&this._sphereTexture.animations&&0(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){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 r=this.getScene(),n=r.getEngine(),a=[],o=[],h=new Ct;let l=this._shaderPath,c=this._options.uniforms,d=this._options.uniformBuffers,u=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,a.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(o.push(G.MatricesIndicesExtraKind),o.push(G.MatricesWeightsExtraKind));const t=e.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),h.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(a.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(a.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else a.push("#define NUM_BONE_INFLUENCERS 0");let f=0;const _=e?e.morphTargetManager:null;if(_){const e=_.supportsUVs&&-1!==a.indexOf("#define UV1"),t=_.supportsTangents&&-1!==a.indexOf("#define TANGENT"),i=_.supportsNormals&&-1!==a.indexOf("#define NORMAL");f=_.numMaxInfluencers||_.numInfluencers,e&&a.push("#define MORPHTARGETS_UV"),t&&a.push("#define MORPHTARGETS_TANGENT"),i&&a.push("#define MORPHTARGETS_NORMAL"),f>0&&a.push("#define MORPHTARGETS"),_.isUsingTextureForTargets&&(a.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),a.push("#define NUM_MORPH_INFLUENCERS "+f);for(let s=0;s0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else a.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),Ht(o,0,a)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&a.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(Pt(c),Dt(this,r,a)),r.fogEnabled&&e?.applyFog&&r.fogMode!==as.FOGMODE_NONE&&(a.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(a.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),d=d.slice(),u=u.slice(),l=this.customShaderNameResolve(this.name,c,d,u,a,o));const p=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,g=p?.effect??null,m=p?.defines??null,T=a.join("\n");let x=g;return m!==T&&(x=n.createEffect(l,{attributes:o,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:T,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:f},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,T,this._materialContext):p&&p.setEffect(x,T),this._onEffectCreatedObservable&&(Hr.effect=x,Hr.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(Hr))),p._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(g!==x&&r.resetCachedMaterial(),p._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const a=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const o=this._options.uniformBuffers;let h=!1;if(n&&o&&o.length>0&&a.getEngine().supportsUniformBuffers)for(let i=0;i0&&Gt(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,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 t=0;tnew Kr(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Kr(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,st.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],a=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>L.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,N.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>N.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,A.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,M.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,b.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,S.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,y.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const a=new pe;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const t=JSON.parse(a.responseText),n=this.Parse(t,i||_.q.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),a.open("GET",t),a.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new pe;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(r.shaderMaterial),o=this.Parse(a,t||_.q.LastCreatedScene,i);o.snippetId=e,s(o)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}var Yr,qr,jr;Kr.SnippetUrl="https://snippet.babylonjs.com",Kr.CreateFromSnippetAsync=Kr.ParseFromSnippetAsync,d("BABYLON.ShaderMaterial",Kr),function(e){e[e.Opaque=Ws.MATERIAL_OPAQUE]="Opaque",e[e.AlphaTest=Ws.MATERIAL_ALPHATEST]="AlphaTest",e[e.AlphaBlend=Ws.MATERIAL_ALPHABLEND]="AlphaBlend"}(Yr||(Yr={}));class Zr{_scene;_renderTargetTexture;_resultPixelsBuffer;constructor(e,t=512){this._scene=e;const i=e.getEngine(),s=this._renderTargetTexture=new St("texture_alpha_checker",t,e,{generateDepthBuffer:!1,generateStencilBuffer:!1,generateMipMaps:!1,type:Mi.TEXTURETYPE_UNSIGNED_BYTE,format:i.isWebGPU||i.version>1?Mi.TEXTUREFORMAT_RED:Mi.TEXTUREFORMAT_RGBA,doNotChangeAspectRatio:!0});s.noPrePassRenderer=!0,s.anisotropicFilteringLevel=1,s.renderParticles=!1,s.optimizeUVAllocation=!0,s.ignoreCameraViewport=!0,s.clearColor=new N(0,0,0,1),this._resultPixelsBuffer=new Uint8Array(t*t*4)}async _renderTexture(e,t,i){const s=Zr._GetShader(this._scene);s.setTexture("textureSampler",e);let r=null;null!==i&&(r=t.subMeshes,t.subMeshes=[t.subMeshes[i]]);const n=this._renderTargetTexture;n.renderList=[t],n.setMaterialForRendering(t,s);const a=t._internalAbstractMeshDataInfo._currentLODIsUpToDate,o=t._internalAbstractMeshDataInfo._currentLOD;t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,t._internalAbstractMeshDataInfo._currentLOD=t;const h=t._nodeDataStorage._isEnabled,l=t._nodeDataStorage._isParentEnabled;t._nodeDataStorage._isEnabled=!0,t._nodeDataStorage._isParentEnabled=!0,n.render(!1,!1),t._nodeDataStorage._isParentEnabled=l,t._nodeDataStorage._isEnabled=h,t._internalAbstractMeshDataInfo._currentLOD=o,t._internalAbstractMeshDataInfo._currentLODIsUpToDate=a;const c=s.getEffect();t.geometry._releaseVertexArrayObject(c);const d=t.subMeshes;for(let e=0,t=d.length;e{this._taskQueue.push(e)})),this._blockRendering=!0;const n=await this._renderTexture(e,t,i);let a=0,o=0,h=0;for(let e=0;e{this._taskQueue.push(e)})),this._blockRendering=!0;const s=await this._renderTexture(e,t,i);for(let e=0;e{e._textureAlphaCheckerShader?.dispose(),e._textureAlphaCheckerShader=null})),e._textureAlphaCheckerShader=t}return e._textureAlphaCheckerShader}static DisposeShader(e){e._textureAlphaCheckerShader?.dispose(),e._textureAlphaCheckerShader=null}}!function(e){e[e.DepthWriteAlphaBlendingWithEvaluation=0]="DepthWriteAlphaBlendingWithEvaluation",e[e.DepthWriteAlphaBlending=1]="DepthWriteAlphaBlending",e[e.AlphaEvaluation=2]="AlphaEvaluation"}(qr||(qr={}));class Qr{renderMethod=qr.DepthWriteAlphaBlendingWithEvaluation;forceDisableAlphaEvaluation=!1;alphaThreshold=195;alphaBlendThreshold=100;alphaEvaluationResolution=512;deleteTextureBufferAfterLoad=!0;_textureLoader=new br;nextStartingAlphaIndex=65536;alphaIndexIncrementsPerModel=1024;_setMeshesAlphaIndex(e){let t=this.nextStartingAlphaIndex;for(let i=0;inull!==g?g:this.forceDisableAlphaEvaluation?null:g=new Zr(l,this.alphaEvaluationResolution),T=new Xr(a,r,n),x=[],E={lengthComputable:!0,loaded:0,total:3*t.length},v=()=>{E.loaded+=1,f?.(E)},A=[];for(let n=0;nthis.setAlphaBlendMode(h,a,o[n],u,m);if(void 0!==f){const e=f.then(_);t.push(e)}else{const e=_();void 0!==e&&t.push(e)}const p=this.loadSphereTexture(e,h,a,s,i[a.sphereTextureIndex]??null,l,c,r,T,u,v);void 0!==p&&t.push(p);const g=this.loadToonTexture(e,h,a,s,i[a.toonTextureIndex]??null,l,c,r,T,u,v);void 0!==g&&t.push(g);const E=this.loadOutlineRenderingProperties(h,a,u);void 0!==E&&t.push(E),x.push(...t),Promise.all(t).then((()=>{this.afterBuildSingleMaterial(h,n,a,s,i,l,r)}))}A.push(h)}this._textureLoader.loadModelTexturesEnd(e);const M=this._textureLoader.onModelTextureLoadedObservable.get(e);return void 0!==M?M.addOnce((()=>{Promise.all(x).then((()=>{g?.dispose(),l._forceBlockMaterialDirtyMechanism(p),null!==d&&this._buildTextureNameMap(t,A,s,i,d),_?.()}))})):Promise.all(x).then((()=>{g?.dispose(),l._forceBlockMaterialDirtyMechanism(p),null!==d&&this._buildTextureNameMap(t,A,s,i,d),_?.()})),A}_buildTextureNameMap(e,t,i,s,r){for(let n=0;n{const s=t.diffuse;e.diffuseColor=new L(s[0],s[1],s[2]);const r=t.specular;e.specularColor=new L(r[0],r[1],r[2]);const n=t.ambient;e.ambientColor=new L(n[0],n[1],n[2]);const a=t.diffuse[3];if(e.alpha=a,0===a)for(let e=0;e{t.backFaceCulling=!(i.flag&ps.Material.Flag.IsDoubleSided);const d=s[r?.imagePathIndex??-1];if(void 0!==d){const i=h.createFullPath(d);let s;const u=h.resolve(i);s=void 0!==u?await this._textureLoader.loadTextureFromBufferAsync(e,i,u instanceof File?u:u.data,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:Mi.TEXTUREFORMAT_RGBA,mimeType:u instanceof File?u.type:u.mimeType}):await this._textureLoader.loadTextureAsync(e,o,d,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:Mi.TEXTUREFORMAT_RGBA});const f=s;null!==f?t.diffuseTexture=f:l.error(`Failed to load diffuse texture: ${i}`),c?.()}else c?.()};async _evaluateDiffuseTextureTransparencyMode(e,t,i,s,r){let n=Number.MIN_SAFE_INTEGER;if(this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation){let s=t>>4&3;if(0==(3^s)&&(s=-1),-1===s){n=Ws.MATERIAL_OPAQUE;const t=r();if(null!==t)for(let s=0;s{if(this.renderMethod===qr.DepthWriteAlphaBlending)return e.diffuseTexture&&(e.diffuseTexture.hasAlpha=!0,e.useAlphaFromDiffuseTexture=!0),e.transparencyMode=Ws.MATERIAL_ALPHABLEND,void(e.forceDepthWrite=!0);if(this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation&&e.alpha<1)return e.diffuseTexture&&(e.diffuseTexture.hasAlpha=!0,e.useAlphaFromDiffuseTexture=!0),e.transparencyMode=Ws.MATERIAL_ALPHABLEND,void(e.forceDepthWrite=!0);const n=e.diffuseTexture,a=t.evaluatedTransparency??-1;if(null!==n){const t=await this._evaluateDiffuseTextureTransparencyMode(n,a,i,s,r);if(null!==t){const i=t!==Ws.MATERIAL_OPAQUE;i&&(n.hasAlpha=!0),e.useAlphaFromDiffuseTexture=i,e.transparencyMode=t,this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation&&(e.forceDepthWrite=i)}}else if(this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation){let t=a>>4&3;0==(3^t)&&(t=0),e.transparencyMode=0===t?Ws.MATERIAL_OPAQUE:Ws.MATERIAL_ALPHABLEND}else{let t=15&a;0==(15^t)&&(t=0),e.transparencyMode=Ws.MATERIAL_OPAQUE}};loadSphereTexture=async(e,t,i,s,r,n,a,o,h,l,c)=>{if(i.sphereTextureMode!==ps.Material.SphereTextureMode.Off){const d=s[r?.imagePathIndex??-1];if(void 0!==d){const s=n.getEngine().isWebGPU||i.sphereTextureMode===ps.Material.SphereTextureMode.Multiply?Mi.TEXTUREFORMAT_RGBA:Mi.TEXTUREFORMAT_RGB,u=h.createFullPath(d);let f;const _=h.resolve(u);f=void 0!==_?await this._textureLoader.loadTextureFromBufferAsync(e,u,_ instanceof File?_:_.data,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:s,mimeType:_ instanceof File?_.type:_.mimeType}):await this._textureLoader.loadTextureAsync(e,o,d,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:s}),null!==f?(t.sphereTexture=f,t.sphereTextureBlendMode=i.sphereTextureMode):l.error(`Failed to load sphere texture: ${u}`),c?.()}else c?.()}else c?.()};loadToonTexture=async(e,t,i,s,r,n,a,o,h,l,c)=>{let d;if(d=i.isSharedToonTexture?i.toonTextureIndex:s[r?.imagePathIndex??-1],void 0!==d){const i=h.createFullPath(d.toString());let s;const u="string"==typeof d?h.resolve(i):void 0;s=void 0!==u?await this._textureLoader.loadTextureFromBufferAsync(e,i,u instanceof File?u:u.data,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:n.getEngine().isWebGPU?Mi.TEXTUREFORMAT_RGBA:Mi.TEXTUREFORMAT_RGB,mimeType:u instanceof File?u.type:u.mimeType}):await this._textureLoader.loadTextureAsync(e,o,d,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:n.getEngine().isWebGPU?Mi.TEXTUREFORMAT_RGBA:Mi.TEXTUREFORMAT_RGB}),null!==s?t.toonTexture=s:l.error(`Failed to load toon texture: ${i}`),c?.()}else c?.()};loadOutlineRenderingProperties=(e,t,i)=>{if(t.flag&ps.Material.Flag.EnabledToonEdge){void 0===as.prototype.getMmdOutlineRenderer&&i.warn('MMD Outline Renderer is not available. Please import "babylon-mmd/esm/Loader/mmdOutlineRenderer".'),e.renderOutline=!0,e.outlineWidth=t.edgeSize;const s=t.edgeColor;e.outlineColor=new L(s[0],s[1],s[2]),e.outlineAlpha=s[3]}};afterBuildSingleMaterial=()=>{}}class $r{lengthComputable;total;_onProgress;_unprocessedTasks;_processingTasks;_endedTaskNames;_endedTasksTotal;constructor(e,t,i){this.lengthComputable=e;let s=0;for(let e=0;e=i.cost&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=i.cost))}setTaskProgress(e,t){const i=this._getTaskState(e);return null!==i&&(i.progress=t,i.progress>=i.cost&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=i.cost),!0)}setTaskProgressRatio(e,t,i){const s=this._getTaskState(e);return null!==s&&(s.progress=i?Math.floor(s.cost*t):s.cost*t,s.progress>=s.cost&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=s.cost),!0)}endTask(e){const t=this._getTaskState(e);null!==t&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=t.cost)}invokeProgressEvent(){null!==this._onProgress&&this._onProgress({lengthComputable:this.lengthComputable,loaded:this.loaded,total:this.total})}get loaded(){let e=this._endedTasksTotal;for(const[t,i]of this._processingTasks)e+=i.progress;return e}}class Jr{name;extensions;materialBuilder;useSdef;buildSkeleton;buildMorph;boundingBoxMargin;preserveSerializationData;_loggingEnabled;log;warn;error;static _SharedStandardMaterialBuilder=new Qr;constructor(e,t){this.name=e,this.extensions=t,this.materialBuilder=Jr._SharedStandardMaterialBuilder,this.useSdef=!0,this.buildSkeleton=!0,this.buildMorph=!0,this.boundingBoxMargin=10,this.preserveSerializationData=!1,this._loggingEnabled=!1,this.log=this._logDisabled,this.warn=this._warnDisabled,this.error=this._errorDisabled}importMeshAsync(e,t,i,s,r,n){return this._loadAsyncInternal(t,null,i,s,r)}loadAsync(e,t,i,s,r){return this._loadAsyncInternal(e,null,t,i,s).then((()=>{}))}loadAssetContainerAsync(e,t,i,s,r){const n=new ar(e);return this._loadAsyncInternal(e,n,t,i,s).then((()=>n))}async _loadAsyncInternal(e,t,i,s,r){const n=await this._parseFileAsync(i.arrayBuffer),a=new $r(!0,this._getProgressTaskCosts(i,n),r??null);a.endTask("Parse"),a.invokeProgressEvent(),e._blockEntityCollection=!!t;const o=new Zs(n.header.modelName,e);o._parentContainer=t,e._blockEntityCollection=!1,o.setEnabled(!1);const h=await this._buildGeometryAsync(i,n,o,e,t,a),l=i.preserveSerializationData?new Map:null,{materials:c,multiMaterials:d,textureLoadPromise:u}=await this._buildMaterialAsync(i,n,o,h.meshes,l,e,t,s,a),f=[];let _=null;i.buildSkeleton?_=await this._buildSkeletonAsync(i,n,h.meshes,e,t,f,a):a.endTask("Build Skeleton");const p=[];let g=null;if(i.buildMorph&&(g=await this._buildMorphAsync(i,n,h,e,t,p,a)),0!==i.boundingBoxMargin&&this._applyBoundingBoxMargin(h.meshes,i.boundingBoxMargin),o.metadata={isMmdModel:!0,header:{modelName:n.header.modelName,englishModelName:n.header.englishModelName,comment:n.header.comment,englishComment:n.header.englishComment},bones:f,morphs:p,rigidBodies:n.rigidBodies,joints:n.joints,meshes:h.meshes,materials:c,skeleton:_},i.preserveSerializationData){const e=[],t=n.materials;for(let i=0;i4,u=d?this.getVerticesData(G.MatricesIndicesExtraKind):null,f=d?this.getVerticesData(G.MatricesWeightsExtraKind):null,_=e.getTransformMatrices(this),p=M.Zero(),g=new y,m=new y,T=new y,x=new y,E=new S,v=new S,A=new M,b=i._sourcePositions,I=i._sourceNormals;let R,C=0;for(let e=0;e0&&(y.FromFloat32ArrayToRefScaled(_,Math.floor(16*l[C+R]),i,m),g.addToSelf(m));if(d)for(R=0;R<4;R++)i=f[C+R],i>0&&(y.FromFloat32ArrayToRefScaled(_,Math.floor(16*u[C+R]),i,m),g.addToSelf(m));M.TransformCoordinatesFromFloatsToRef(b[e],b[e+1],b[e+2],g,p),p.toArray(s,e),t&&(M.TransformNormalFromFloatsToRef(I[e],I[e+1],I[e+2],g,p),p.toArray(r,e)),g.reset()}else{const i=c[C+0],n=c[C+1];y.FromArrayToRef(_,Math.floor(16*l[C+0]),T),y.FromArrayToRef(_,Math.floor(16*l[C+1]),x),S.FromRotationMatrixToRef(T,E),S.FromRotationMatrixToRef(x,v),y.FromQuaternionToRef(S.SlerpToRef(E,v,n,E),m),M.TransformCoordinatesFromFloatsToRef(b[e]-a[e],b[e+1]-a[e+1],b[e+2]-a[e+2],m,A),M.TransformCoordinatesFromFloatsToRef(o[e],o[e+1],o[e+2],T,p).scaleAndAddToRef(i,A),M.TransformCoordinatesFromFloatsToRef(h[e],h[e+1],h[e+2],x,p).scaleAndAddToRef(n,A),A.toArray(s,e),t&&(M.TransformNormalFromFloatsToRef(I[e],I[e+1],I[e+2],m,A),A.toArray(r,e))}}return this.updateVerticesData(G.PositionKind,s),t&&this.updateVerticesData(G.NormalKind,r),this}}class sn extends Jr{referenceFiles;constructor(e,t){super(e,t),this.referenceFiles=[]}loadFile(e,t,i,s,r,n,a){const o=this.materialBuilder,h=this.useSdef,l=this.buildSkeleton,c=this.buildMorph,d=this.boundingBoxMargin,u=this.referenceFiles,f=this.preserveSerializationData;return e._loadFile(t,((e,i)=>{const r={arrayBuffer:e,pmFileId:t instanceof File?en.GetId(t).toString():t,materialBuilder:o,useSdef:h,buildSkeleton:l,buildMorph:c,boundingBoxMargin:d,referenceFiles:u,preserveSerializationData:f};s(r,i)}),r,!0,n,a)}_getProgressTaskCosts(e,t){const i=super._getProgressTaskCosts(e,t);if(i.push({name:"Build Geometry",cost:t.indices.length}),e.buildMorph){let e=0;const s=t.morphs;for(let t=0;t{l=e.materialBuilder.buildMaterials(i.uniqueId,t.materials,c,t.textures,o,"file:"+e.pmFileId+"_",e.referenceFiles,d,s,n,a,r,this,(e=>{e.lengthComputable&&(h.setTaskProgressRatio("Texture Load",e.loaded/e.total,!0),h.invokeProgressEvent())}),(()=>u()))})),f=Array.isArray(l)?l:await l;for(let e=0;ePromise.reject(e)))}});class rn{_vertexIndexSize;_textureIndexSize;_materialIndexSize;_boneIndexSize;_morphIndexSize;_rigidBodyIndexSize;constructor(e,t,i,s,r,n){this._vertexIndexSize=e,this._textureIndexSize=t,this._materialIndexSize=i,this._boneIndexSize=s,this._morphIndexSize=r,this._rigidBodyIndexSize=n}getVertexIndex(e){switch(this._vertexIndexSize){case 1:return e.getUint8();case 2:return e.getUint16();case 4:return e.getInt32();default:throw new Error(`Invalid vertexIndexSize: ${this._vertexIndexSize}`)}}_getNonVertexIndex(e,t){switch(t){case 1:return e.getInt8();case 2:return e.getInt16();case 4:return e.getInt32();default:throw new Error(`Invalid indexSize: ${t}`)}}getTextureIndex(e){return this._getNonVertexIndex(e,this._textureIndexSize)}getMaterialIndex(e){return this._getNonVertexIndex(e,this._materialIndexSize)}getBoneIndex(e){return this._getNonVertexIndex(e,this._boneIndexSize)}getMorphIndex(e){return this._getNonVertexIndex(e,this._morphIndexSize)}getRigidBodyIndex(e){return this._getNonVertexIndex(e,this._rigidBodyIndexSize)}}class nn{constructor(){}static async ParseAsync(e,t=new xs){const i=new Es(e),s=this._ParseHeader(i,t),r=new rn(s.vertexIndexSize,s.textureIndexSize,s.materialIndexSize,s.boneIndexSize,s.morphIndexSize,s.rigidBodyIndexSize),n=await this._ParseVerticesAsync(i,r,s),a=this._ParseIndices(i,r,s),o=this._ParseTextures(i),h=this._ParseMaterials(i,r),l=this._ParseBones(i,r),c=this._ParseMorphs(i,r),d=this._ParseDisplayFrames(i,r),u=this._ParseRigidBodies(i,r),f=this._ParseJoints(i,r),_=s.version<=2?[]:this._ParseSoftBodies(i,r,s);return i.bytesAvailable>0&&t.warn(`There are ${i.bytesAvailable} bytes left after parsing`),{header:s,vertices:n,indices:a,textures:o,materials:h,bones:l,morphs:c,displayFrames:d,rigidBodies:u,joints:f,softBodies:_}}static _ParseHeader(e,t){if(e.bytesAvailable<17)throw new RangeError("is not pmx file");const i=e.getSignatureString(3);if("PMX"!==i)throw new RangeError("is not pmx file");e.getInt8();const s=e.getFloat32(),r=e.getUint8(),n=e.getUint8();e.initializeTextDecoder(n===ps.Header.Encoding.Utf8?"utf-8":"utf-16le");const a=e.getUint8(),o=e.getUint8(),h=e.getUint8(),l=e.getUint8(),c=e.getUint8(),d=e.getUint8(),u=e.getUint8();if(r<8)throw new Error(`Invalid globalsCount: ${r}`);if(8setTimeout(e,0))),n=performance.now())}return r}static _ParseIndices(e,t,i){const s=e.getInt32(),r=new ArrayBuffer(s*i.vertexIndexSize);let n;switch(i.vertexIndexSize){case 1:n=new Uint8Array(r);break;case 2:n=new Uint16Array(r);break;case 4:n=new Int32Array(r);break;default:throw new Error(`Invalid vertexIndexSize: ${i.vertexIndexSize}`)}for(let i=0;iPromise.reject(e)))}});class an{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((e=>{e.type!==Ui.POINTERDOWN?e.type===Ui.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=_e.j.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??_e.j.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}on.EASINGMODE_EASEIN=0,on.EASINGMODE_EASEOUT=1,on.EASINGMODE_EASEINOUT=2;class hn{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((e=>{if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):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}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(hn.EasingFunction.setEasingMode(hn.EasingMode),this._radiusBounceTransition=mr.CreateAnimation("radius",mr.ANIMATIONTYPE_FLOAT,60,hn.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=mr.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()}}hn.EasingFunction=new class extends on{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)}}(.3),hn.EasingMode=on.EASINGMODE_EASEOUT;class ln{constructor(){this.onTargetFramingAnimationEndObservable=new se.cP,this._mode=ln.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();ln.EasingFunction.setEasingMode(ln.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Ui.POINTERDOWN?e.type===Ui.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,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 M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new M(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),h&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===ln.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=_e.j.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=mr.CreateAnimation("beta",mr.ANIMATIONTYPE_FLOAT,60,ln.EasingFunction));const e=mr.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=_e.j.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&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}ln.EasingFunction=new class extends on{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)}},ln.EasingMode=on.EASINGMODE_EASEINOUT,ln.IgnoreBoundsSizeMode=0,ln.FitFrustumSidesMode=1,ce.AddNodeConstructor("TargetCamera",((e,t)=>()=>new cn(e,M.Zero(),t)));class cn extends ni{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=M.Zero(),this._tmpTargetVector=M.Zero(),this.cameraDirection=new M(0,0,0),this.cameraRotation=new A(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new S,this.rotation=new M(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=M.Zero(),this._initialFocalDistance=1,this._viewMatrix=y.Zero(),this._camMatrix=y.Zero(),this._cameraTransformMatrix=y.Zero(),this._cameraRotationMatrix=y.Zero(),this._referencePoint=new M(0,0,1),this._transformedReferencePoint=M.Zero(),this._deferredPositionUpdate=new M,this._deferredRotationQuaternionUpdate=new S,this._deferredRotationUpdate=new M,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=M.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)}_initCache(){super._initCache(),this._cache.lockedTarget=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new S(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()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=a),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),y.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&&S.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)return this.parent.getWorldMatrix().invertToRef(R.Matrix[0]),M.TransformNormalToRef(this.cameraDirection,R.Matrix[0],R.Vector3[0]),this._deferredPositionUpdate.addInPlace(R.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));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;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(S.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();this.attached[t]?k.V.Warn("camera input of type "+t+" already exists on camera"):(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)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}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=!ni.ForceAttachControlToAlwaysPreventDefault&&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 e in this.attached){const i=this.attached[e],s=he.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=dn[e];if(i){const s=t[e],r=he.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=dn[this.attached[t].getClassName()];if(i){const s=he.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class fn{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Xe.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const a=n.event,o="touch"===a.pointerType;if(n.type!==Ui.POINTERMOVE&&-1===this.buttons.indexOf(a.button))return;const h=a.target;if(this._altKey=a.altKey,this._ctrlKey=a.ctrlKey,this._metaKey=a.metaKey,this._shiftKey=a.shiftKey,this._buttonsPressed=a.buttons,t.isPointerLock){const e=a.movementX,t=a.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==Ui.POINTERDOWN&&o&&this._pointA?.pointerId!==a.pointerId&&this._pointB?.pointerId!==a.pointerId)return;if(n.type!==Ui.POINTERDOWN||-1!==this._currentActiveButton&&!o)if(n.type===Ui.POINTERDOUBLETAP)this.onDoubleTap(a.pointerType);else if(n.type!==Ui.POINTERUP||this._currentActiveButton!==a.button&&!o){if(n.type===Ui.POINTERMOVE)if(e||a.preventDefault(),this._pointA&&null===this._pointB){const e=a.clientX-this._pointA.x,t=a.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=a.clientX,this._pointA.y=a.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===a.pointerId?this._pointA:this._pointB;e.x=a.clientX,e.y=a.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,o=t*t+i*i,h={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:a.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,o,r,h),r=h,s=o}}else{try{h?.releasePointerCapture(a.pointerId)}catch(e){}o||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==a.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==a.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(a),e||a.preventDefault()}else{try{h?.setPointerCapture(a.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType};else{if(null!==this._pointB)return;this._pointB={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType}}-1!==this._currentActiveButton||o||(this._currentActiveButton=a.button),this.onButtonDown(a),e||(a.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ui.POINTERDOWN|Ui.POINTERUP|Ui.POINTERMOVE|Ui.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Xe.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Xe.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}z([q()],fn.prototype,"buttons",void 0);class _n extends fn{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(0!==this.panningSensibility&&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||_n.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(t-e)*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(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,r,n){0===i&&null===r||0===s&&null===n||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,s),this._computeMultiTouchPanning(r,n)):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(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}_n.MinimumRadiusForPinch=.001,z([q()],_n.prototype,"buttons",void 0),z([q()],_n.prototype,"angularSensibilityX",void 0),z([q()],_n.prototype,"angularSensibilityY",void 0),z([q()],_n.prototype,"pinchPrecision",void 0),z([q()],_n.prototype,"pinchDeltaPercentage",void 0),z([q()],_n.prototype,"useNaturalPinchZoom",void 0),z([q()],_n.prototype,"pinchZoom",void 0),z([q()],_n.prototype,"panningSensibility",void 0),z([q()],_n.prototype,"multiTouchPanning",void 0),z([q()],_n.prototype,"multiTouchPanAndZoom",void 0),dn.ArcRotateCameraPointersInput=_n;class pn{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=Xe.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===Wi.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Xe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ui.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===Ki.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=P.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);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,Ui.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=et.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,y.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=M.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=R.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)()=>new Tn(e,0,0,1,M.Zero(),t)));class Tn extends cn{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 y,this._upToYMatrix=new y,this._upVector=M.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){y.RotationAlignToRef(M.UpReadOnly,this._upVector,this._yToUpMatrix),y.RotationAlignToRef(this._upVector,M.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}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}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 null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new hn,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new ln,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new an,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,a=!0){super(e,M.Zero(),n,a),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=M.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=A.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new y,this.panningAxis=new M(1,1,0),this._transformedDirection=new M,this.mapPanning=!1,this.onMeshTargetChangedObservable=new se.cP,this.checkCollisions=!1,this.collisionRadius=new M(.5,.5,.5),this._previousPosition=M.Zero(),this._collisionVelocity=M.Zero(),this._newPosition=M.Zero(),this._computationVector=M.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let a=Math.sin(this.beta);0===a&&(a=1e-4);const o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*a,this.radius*n,this.radius*r*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let h=this.upVector;this.allowUpsideDown&&this.beta<0&&(h=h.clone(),h=h.negate()),this._computeViewMatrix(this._position,o,h),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=M.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new mn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new M(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=A.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 e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_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)}attachControl(e,t,i=!0,s=2){const r=arguments;t=Xe.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||M.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?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+=2*t*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){if(s=this.overrideCloneAlphaBetaRadius??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 t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,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);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||M.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Zs.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(void 0===e.min){const t=e||this.getScene().meshes;i=Zs.MinMax(t),s=M.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=Zs.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ni.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ni.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ni.RIG_MODE_STEREOSCOPIC_INTERLACED:case ni.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new Tn(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 ni.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ni.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ni.RIG_MODE_STEREOSCOPIC_INTERLACED:case ni.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=M.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),a=n*r,o=.5*s*i,h=o*Math.sqrt(1+1/(a*a)),l=o*Math.sqrt(1+1/(n*n));return Math.max(h,l)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}z([q()],Tn.prototype,"alpha",void 0),z([q()],Tn.prototype,"beta",void 0),z([q()],Tn.prototype,"radius",void 0),z([q()],Tn.prototype,"overrideCloneAlphaBetaRadius",void 0),z([J("target")],Tn.prototype,"_target",void 0),z([ee("targetHost")],Tn.prototype,"_targetHost",void 0),z([q()],Tn.prototype,"inertialAlphaOffset",void 0),z([q()],Tn.prototype,"inertialBetaOffset",void 0),z([q()],Tn.prototype,"inertialRadiusOffset",void 0),z([q()],Tn.prototype,"lowerAlphaLimit",void 0),z([q()],Tn.prototype,"upperAlphaLimit",void 0),z([q()],Tn.prototype,"lowerBetaLimit",void 0),z([q()],Tn.prototype,"upperBetaLimit",void 0),z([q()],Tn.prototype,"lowerRadiusLimit",void 0),z([q()],Tn.prototype,"upperRadiusLimit",void 0),z([q()],Tn.prototype,"inertialPanningX",void 0),z([q()],Tn.prototype,"inertialPanningY",void 0),z([q()],Tn.prototype,"pinchToPanMaxDistance",void 0),z([q()],Tn.prototype,"panningDistanceLimit",void 0),z([J()],Tn.prototype,"panningOriginTarget",void 0),z([q()],Tn.prototype,"panningInertia",void 0),z([q()],Tn.prototype,"zoomToMouseLocation",null),z([q()],Tn.prototype,"zoomOnFactor",void 0),z([$()],Tn.prototype,"targetScreenOffset",void 0),z([q()],Tn.prototype,"allowUpsideDown",void 0),z([q()],Tn.prototype,"useInputToRestoreState",void 0),d("BABYLON.ArcRotateCamera",Tn);class xn extends Ze{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=y.Identity(),this._projectionMatrix=y.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=M.Zero()),M.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=M.Zero()),M.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}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=M.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=M.Cross(this.direction,Os.Y),t=M.Cross(e,this.direction);return M.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=M.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=y.Identity()),y.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 void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?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=R.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),M.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(M.Dot(t,M.Up()))&&(t.z=1e-13);const s=R.Vector3[1];return i.addToRef(t,s),y.LookAtLHToRef(i,s,M.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}z([J()],xn.prototype,"position",null),z([J()],xn.prototype,"direction",null),z([q()],xn.prototype,"shadowMinZ",null),z([q()],xn.prototype,"shadowMaxZ",null),ce.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new En(e,M.Zero(),t)));class En extends xn{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Ze.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&y.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=M.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;y.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?o:a,h?a:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}z([q()],En.prototype,"shadowFrustumSize",null),z([q()],En.prototype,"shadowOrthoScale",null),z([q()],En.prototype,"autoUpdateExtends",void 0),z([q()],En.prototype,"autoCalcShadowZBounds",void 0),z([q("orthoLeft")],En.prototype,"_orthoLeft",void 0),z([q("orthoRight")],En.prototype,"_orthoRight",void 0),z([q("orthoTop")],En.prototype,"_orthoTop",void 0),z([q("orthoBottom")],En.prototype,"_orthoBottom",void 0),d("BABYLON.DirectionalLight",En),ce.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new vn(e,M.Zero(),t)));class vn extends Ze{constructor(e,t,i){super(e,i),this.groundColor=new L(0,0,0),this.direction=t||M.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=M.Normalize(e.subtract(M.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=M.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=M.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=y.Identity()),this._worldMatrix}getTypeID(){return Ze.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}z([Z()],vn.prototype,"groundColor",void 0),z([J()],vn.prototype,"direction",void 0),d("BABYLON.HemisphericLight",vn),Zs._GroundMeshParser=(e,t)=>An.Parse(e,t);class An extends Zs{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);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=R.Matrix[5];i.invertToRef(s);const r=R.Vector3[8];if(M.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return M.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new M(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=R.Matrix[5];s.invertToRef(r);const n=R.Vector3[8];if(M.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return M.TransformNormalFromFloatsToRef(a.x,a.y,a.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){c=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new M(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),d=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[d]/255,f=e.buffer[d+1]/255,_=e.buffer[d+2]/255;const p=e.buffer[d+3]/255;c&&(u=1-u,f=1-f,_=1-_);const g=u*h.r+f*h.g+_*h.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*g:e.minHeight-a,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,d=i[3*a+1]>=e.minHeight;l&&c&&d&&(t.push(s),t.push(r),t.push(a)),i[3*h+1]>=e.minHeight&&l&&d&&(t.push(h),t.push(s),t.push(a))}Ps.ComputeNormals(i,t,s);const d=new Ps;return d.indices=t,d.positions=i,d.normals=s,d.uvs=r,d}function yn(e,t={},i){const s=new An(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Mn(t).applyToMesh(s,t.updatable),s._setReady(!0),s}Ps.CreateGround=Mn,Ps.CreateTiledGround=bn,Ps.CreateGroundFromHeightMap=Sn,Zs.CreateGround=(e,t,i,s,r,n)=>yn(e,{width:t,height:i,subdivisions:s,updatable:n},r),Zs.CreateTiledGround=(e,t,i,s,r,n,a,o,h)=>function(e,t,i=null){const s=new Zs(e,i);return bn(t).applyToMesh(s,t.updatable),s}(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:a,updatable:h},o),Zs.CreateGroundFromHeightMap=(e,t,i,s,r,n,a,o,h,l,c)=>function(e,t,i={},s=null){const r=i.width||10,n=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,h=i.maxHeight||1,l=i.colorFilter||new L(.3,.59,.11),c=i.alphaFilter||0,d=i.updatable,u=i.onReady;s=s||_.q.LastCreatedScene;const f=new An(e,s);let p;f._subdivisionsX=a,f._subdivisionsY=a,f._width=r,f._height=n,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((a+1)*(a+1)));const g=(e,t,i)=>{Sn({width:r,height:n,subdivisions:a,minHeight:o,maxHeight:h,colorFilter:l,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(f,d),u&&u(f,p),f._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);g(r,t,i)};Xe.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else g(t.data,t.width,t.height);return f}(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:a,updatable:h,onReady:l,alphaFilter:c},o);gt.l.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class In{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const a=e.getMaterial();if(!a)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return a.isReadyForSubMesh(e.getMesh(),e,t);const o=[],h=[G.PositionKind];let l=!1,c=!1;if(a){const e=a.needAlphaTesting(),t=a.getAlphaTestTexture(),i=t&&t.hasAlpha&&(a.useAlphaFromDiffuseTexture||a._useAlphaFromAlbedoTexture);t&&(e||i)&&(o.push("#define DIFFUSE"),r.isVerticesDataPresent(G.UV2Kind)&&1===t.coordinatesIndex?(o.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(G.UVKind)&&(o.push("#define DIFFUSEUV1"),l=!0),e&&(o.push("#define ALPHATEST"),o.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||o.push("#define DIFFUSE_ISLINEAR"));const s=a.opacityTexture;s&&(o.push("#define OPACITY"),r.isVerticesDataPresent(G.UV2Kind)&&1===s.coordinatesIndex?(o.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(G.UVKind)&&(o.push("#define OPACITYUV1"),l=!0))}i&&(o.push("#define EMISSIVE"),r.isVerticesDataPresent(G.UV2Kind)&&1===i.coordinatesIndex?(o.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(G.UVKind)&&(o.push("#define EMISSIVEUV1"),l=!0),i.gammaSpace||o.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(G.ColorKind)&&r.hasVertexAlpha&&a.transparencyMode!==Ws.MATERIAL_OPAQUE&&(h.push(G.ColorKind),o.push("#define VERTEXALPHA")),l&&(h.push(G.UVKind),o.push("#define UV1")),c&&(h.push(G.UV2Kind),o.push("#define UV2"));const d=new Ct;if(r.useBones&&r.computeBonesUsingShaders){h.push(G.MatricesIndicesKind),h.push(G.MatricesWeightsKind),r.numBoneInfluencers>4&&(h.push(G.MatricesIndicesExtraKind),h.push(G.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?o.push("#define BONETEXTURE"):o.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,r)}else o.push("#define NUM_BONE_INFLUENCERS 0");const u=r.morphTargetManager;let f=0;u&&(f=u.numMaxInfluencers||u.numInfluencers,f>0&&(o.push("#define MORPHTARGETS"),o.push("#define NUM_MORPH_INFLUENCERS "+f),u.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),Ut(h,r,f))),t&&(o.push("#define INSTANCES"),Vt(h),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),Dt(a,this._scene,o),this._addCustomEffectDefines(o);const _=e._getDrawWrapper(void 0,!0),p=_.defines,g=o.join("\n");if(p!==g){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Pt(e),_.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:f}),g)}return _.effect.isReady()}render(){for(let e=0;el.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[G.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 Xe.Instantiate(e.customType).Parse(e,t,i)}}In._SceneComponentInitialization=e=>{throw(0,re.n)("EffectLayerSceneComponent")},z([q()],In.prototype,"name",void 0),z([te()],In.prototype,"neutralColor",void 0),z([q()],In.prototype,"isEnabled",void 0),z([K(11,void 0)],In.prototype,"camera",null),z([q()],In.prototype,"renderingGroupId",null),z([q()],In.prototype,"disableBoundingBoxesFromEffectLayer",void 0);gt.l.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";gt.l.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;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;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",mi.AddParser(pi.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===ni.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==ni.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(pi.NAME_EFFECTLAYER);t||(t=new Rn(e),e._addComponent(t))},mi.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new Rt("GlowLayerVBP1",new A(0,1),n,{width:e,height:t},null,st.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Rt("GlowLayerHBP2",new A(1,0),n,{width:s,height:r},null,st.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new Rt("GlowLayerVBP2",new A(0,1),n,{width:s,height:r},null,st.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Ws.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=he.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Cn(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return he.Parse((()=>new Pn(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}z([q()],Pn.prototype,"colorAmount",void 0),z([q()],Pn.prototype,"edgeAmount",void 0),d("BABYLON.SharpenPostProcess",Pn);gt.l.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class Dn extends It{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=_.q.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new Ii}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,a=0,o){super(e,"imageProcessing",[],[],t,i,s,r,n,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];Ii&&(Ii.PrepareSamplers(t,this._defines),Ii.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}z([q()],Dn.prototype,"_fromLinearSpace",void 0);gt.l.ShadersStore.chromaticAberrationPixelShader="uniform sampler2D textureSampler; \nuniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}";class On extends It{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,s,r,n,a,o,h=0,l=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],s,r,n,a,o,null,h,void 0,null,l),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new A(.707,.707),this.centerPosition=new A(.5,.5),this.screenWidth=t,this.screenHeight=i,this.onApplyObservable.add((e=>{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return he.Parse((()=>new On(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}z([q()],On.prototype,"aberrationAmount",void 0),z([q()],On.prototype,"radialIntensity",void 0),z([q()],On.prototype,"direction",void 0),z([q()],On.prototype,"centerPosition",void 0),z([q()],On.prototype,"screenWidth",void 0),z([q()],On.prototype,"screenHeight",void 0),d("BABYLON.ChromaticAberrationPostProcess",On);gt.l.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class Fn extends It{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,a=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,a,void 0,null,o),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return he.Parse((()=>new Fn(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}z([q()],Fn.prototype,"intensity",void 0),z([q()],Fn.prototype,"animated",void 0),d("BABYLON.GrainPostProcess",Fn);gt.l.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_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 he.Parse((()=>new wn(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}d("BABYLON.FxaaPostProcess",wn);class Ln{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Xe.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Xe.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Xe.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}z([q()],Ln.prototype,"_name",void 0);class Nn{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=Xe.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Xe.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}gt.l.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class Bn extends It{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,a,o=0,h=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,a,null,o,void 0,null,h),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void k.V.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}z([q()],Bn.prototype,"lensSize",void 0),z([q()],Bn.prototype,"fStop",void 0),z([q()],Bn.prototype,"focusDistance",void 0),z([q()],Bn.prototype,"focalLength",void 0),d("BABYLON.CircleOfConfusionPostProcess",Bn);class Un extends Rt{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,a,o=null,h=st.BILINEAR_SAMPLINGMODE,l,c,d=0,u=!1,f=5){super(e,i,s,r,n,2,l,c,d,"#define DOF 1\n",u,f),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add((e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)}))}}z([q()],Un.prototype,"direction",void 0),d("BABYLON.DepthOfFieldBlurPostProcess",Un);gt.l.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class kn extends It{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,a,o,h,l=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,a,o,h,null,l,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var Vn;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(Vn||(Vn={}));class Gn extends Nn{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=Vn.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),a=n.isWebGPU||n.version>1?6:5;this._circleOfConfusion=new Bn("circleOfConfusion",t,1,null,st.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,h=15;switch(i){case Vn.High:o=3,h=51;break;case Vn.Medium:o=2,h=31;break;default:h=15,o=1}const l=h/Math.pow(2,o-1);let c=1;for(let t=0;t\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class zn extends It{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,a,o=0,h=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,a,null,o,void 0,null,h),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,n)),e.setFloat("exposure",this._exposure)}))}}z([q()],zn.prototype,"threshold",void 0),d("BABYLON.ExtractHighlightsPostProcess",zn);gt.l.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class Wn extends It{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,a,o,h,l=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,a,o,h,null,l,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}z([q()],Wn.prototype,"weight",void 0),d("BABYLON.BloomMergePostProcess",Wn);class Xn extends Nn{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new zn("highlights",1,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new Rt("horizontal blur",new A(1,0),10,t,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Rt("vertical blur",new A(0,1),10,t,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new Wn("bloomMerge",this._downscale,this._blurY,i,t,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;tthis.sharpen),!0),this.depthOfField=new Gn(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add((()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new Xn(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new On("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,st.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new Nn(a,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new Fn("Grain",1,null,st.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new Nn(a,this.GrainPostProcessId,(()=>this.grain),!0);let o=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,o?Xe.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new Dn("imageProcessing",1,null,st.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new Nn(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new wn("fxaa",1,null,st.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new Nn(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&k.V.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew Yn(e._name,e._name._hdr,t)),e,t,i)}}var qn,jn,Zn;z([q()],Yn.prototype,"sharpenEnabled",null),z([q()],Yn.prototype,"bloomKernel",null),z([q()],Yn.prototype,"_bloomWeight",void 0),z([q()],Yn.prototype,"_bloomThreshold",void 0),z([q()],Yn.prototype,"_hdr",void 0),z([q()],Yn.prototype,"bloomWeight",null),z([q()],Yn.prototype,"bloomThreshold",null),z([q()],Yn.prototype,"bloomScale",null),z([q()],Yn.prototype,"bloomEnabled",null),z([q()],Yn.prototype,"depthOfFieldEnabled",null),z([q()],Yn.prototype,"depthOfFieldBlurLevel",null),z([q()],Yn.prototype,"fxaaEnabled",null),z([q()],Yn.prototype,"samples",null),z([q()],Yn.prototype,"imageProcessingEnabled",null),z([q()],Yn.prototype,"glowLayerEnabled",null),z([q()],Yn.prototype,"chromaticAberrationEnabled",null),z([q()],Yn.prototype,"grainEnabled",null),d("BABYLON.DefaultRenderingPipeline",Yn),function(e){e.isMmdMesh=function(e){return!(null===e.metadata||!e.metadata.isMmdModel)},e.isMmdSkinnedMesh=function(e){return!(null===e.metadata||!e.metadata.isMmdModel)&&null!==e.metadata.skeleton}}(qn||(qn={})),function(e){e.isSerializationMetadata=function(e){return!0===e.containsSerializationData}}(jn||(jn={}));class Qn{_dataView;_encoder;_offset;constructor(e){this._dataView=new DataView(e),this._encoder=new TextEncoder,this._offset=0}get offset(){return this._offset}set offset(e){this._offset=e}setUint8(e){this._dataView.setUint8(this._offset,e),this._offset+=1}setUint8Array(e){const t=this._dataView;for(let i=0;i0;){const e=t.pop(),i=r.get(e),s=e.children;for(let e=0;e{const t=e.children;for(let s=0;s{const i=s.get(e);if(void 0!==i)for(let e=0;ee.texture===v)):-1,M=l.sphereTexture,b=M?g.findIndex((e=>e.texture===M)):-1,S=l.sphereTextureBlendMode??ps.Material.SphereTextureMode.Off,y=l.toonTexture,I=!!y&&y.name.startsWith("file:shared_toon_texture_")&&y.name.length<=27&&!isNaN(Number(y.name.substring(25)));let R;R=I?Number(y.name.substring(25))-1:y?g.findIndex((e=>e.texture===y)):-1;const C={name:i,englishName:a,diffuse:h,specular:c,shininess:u,ambient:f,evaluatedTransparency:_,flag:p,edgeColor:x,edgeSize:E,textureIndex:A,sphereTextureIndex:b,sphereTextureMode:S,isSharedToonTexture:I,toonTextureIndex:R,comment:e?.comment??"",linkedMaterial:l};m.push(C)}}}}const x=new Array(a.morphs.length).fill(null);for(let e=0;ee.linkedMaterial===r));M.setInt32(n),M.setUint32(s.verticesStart),M.setUint32(s.verticesCount),M.setUint32(s.indexStart),M.setUint32(s.indexCount)}}else{const e=t.material,i=m.findIndex((t=>t.linkedMaterial===e));M.setInt32(i)}const r=i.getVerticesData(G.PositionKind),n=r.length/3;M.setUint32(n),M.setFloat32Array(r);let a=i.getVerticesData(G.NormalKind);if(a.length!==3*n){this.warn(`mesh ${t.name} normals vertex count is different from positions vertex count`);const e=new Float32Array(3*n);e.set(a),a=e}M.setFloat32Array(a);let o=i.getVerticesData(G.UVKind);if(o.length!==2*n){this.warn(`mesh ${t.name} uv vertex count is different from positions vertex count`);const e=new Float32Array(2*n);e.set(o),o=e}M.setFloat32Array(o);const l=[];{const e=i.getVerticesData(os.AdditionalUV1Kind);null!==e&&l.push(e);const t=i.getVerticesData(os.AdditionalUV2Kind);null!==t&&l.push(t);const s=i.getVerticesData(os.AdditionalUV3Kind);null!==s&&l.push(s);const r=i.getVerticesData(os.AdditionalUV4Kind);null!==r&&l.push(r)}M.setUint8(l.length);for(let e=0;e0;){const s=r.pop(),n=s.getParent();if(n?s.getLocalMatrix().multiplyToRef(n.getFinalMatrix(),s.getFinalMatrix()):t?s.getLocalMatrix().multiplyToRef(t,s.getFinalMatrix()):s.getFinalMatrix().copyFrom(s.getLocalMatrix()),-1!==s._index){const t=null===s._index?i:s._index;s.getAbsoluteInverseBindMatrix().multiplyToArray(s.getFinalMatrix(),e,16*t)}const a=s.getChildren();for(const e of a)r.push(e)}}}this._identity.copyToArray(e,16*this.bones.length)}}}async function ea(e,t=""){const i=[];for(let s=0;s{e.readEntries(t,i)}));i.push(...await ea(s,t+r.name+"/"))}else i.push(r)}return i}class ta{async build(e,t){cs.OverrideEngineCreateEffect(t);const i=Ts.GetPluginForExtension(".pmd");i.loggingEnabled=!0,i.preserveSerializationData=!0;const s=Ts.GetPluginForExtension(".pmx");s.loggingEnabled=!0,s.preserveSerializationData=!0;const r=s.materialBuilder;r.deleteTextureBufferAfterLoad=!1,r.renderMethod=qr.AlphaEvaluation;const n=new as(t);n.ambientColor=new L(.5,.5,.5);const a=new Tn("camera",0,0,45,new M(0,10,0),n);a.maxZ=5e3,a.fov=Math.PI/180*30,a.speed=.5,a.setPosition(new M(0,10,-45)),a.attachControl(e,!0);const o=new vn("hemisphericLight",new M(0,1,0),n);o.intensity=.5,o.specular=new L(0,0,0),o.groundColor=new L(1,1,1);const h=new En("directionalLight",new M(.5,-1,1),n);h.intensity=.5,h.autoCalcShadowZBounds=!1,h.autoUpdateExtends=!1,h.shadowMaxZ=60,h.shadowMinZ=-30,h.orthoTop=54,h.orthoBottom=-3,h.orthoLeft=-30,h.orthoRight=30,h.shadowOrthoScale=0;const l=new Zt(1024,h,!0,a);l.transparencyShadow=!0,l.usePercentageCloserFiltering=!0,l.forceBackFacesOnly=!1,l.bias=.01,l.filteringQuality=Zt.QUALITY_MEDIUM,l.frustumEdgeFalloff=.1,yn("ground1",{width:100,height:100,subdivisions:2,updatable:!1},n).receiveShadows=!0;const c=new Yn("default",!0,n);c.samples=4,c.fxaaEnabled=!0,c.imageProcessingEnabled=!1;const d=new Zr(n),u=async e=>{if(T)return;if(null!==_){for(const e of _.metadata.meshes)l.removeShadowCaster(e);_.dispose(!1,!0),_=null}T=!0,t.displayLoadingUI();const i=e.webkitRelativePath;D.textContent=e.name,_=await Ts.ImportMeshAsync(void 0,i.substring(0,i.lastIndexOf("/")+1),e,n,(i=>t.loadingUIText=`


Loading (${e.name})... ${i.loaded}/${i.total} (${Math.floor(100*i.loaded/i.total)}%)`)).then((e=>{const t=e.meshes[0];return Jn.OverrideComputeTransformMatrices(t.metadata.skeleton),t.metadata.skeleton?._markAsDirty(),t}));{const e=_.metadata.meshes;for(let t=0;te.material===s));for(const e of t)if(await d.hasFragmentsOnlyOpaqueOnGeometry(r,e,null)){p[i]=!1;break}}else p[i]=!1;g[i]=s.transparencyMode??-1}}X(),t.hideLoadingUI(),setTimeout((()=>T=!1),1500)};let f=null,_=null;const p=[],g=[];let m="Alpha Mode",T=!1;const x=e=>{if(null===_)return;const t=_.metadata.materials;if("Alpha Mode"===e)for(let e=0;e{C.style.backgroundColor="#444444",P.style.backgroundColor="#111111",B.style.display="block",O.style.display="block",F.style.display="block",U.style.display="none",G.style.display="none",z.style.display="none"},R.appendChild(C);const P=document.createElement("div");P.textContent="Fix Material",P.style.width="100%",P.style.height="auto",P.style.border="none",P.style.backgroundColor="#111111",P.style.fontSize="20px",P.style.textAlign="center",P.style.color="white",P.style.cursor="pointer",P.onclick=()=>{C.style.backgroundColor="#111111",P.style.backgroundColor="#444444",B.style.display="none",O.style.display="none",F.style.display="none",U.style.display="flex",G.style.display="block",z.style.display="block"},R.appendChild(P);const D=document.createElement("div");D.textContent="No PMX file selected",D.style.width="350px",D.style.height="auto",D.style.fontSize="18px",D.style.marginBottom="10px",D.style.border="1px solid black",D.style.boxSizing="border-box",D.style.padding="10px",D.style.overflow="scroll",b.appendChild(D);const O=document.createElement("div");O.textContent="Files",O.style.width="100%",O.style.height="auto",O.style.fontSize="18px",O.style.backgroundColor="#444444",O.style.color="white",O.style.padding="2px 5px",O.style.boxSizing="border-box",b.appendChild(O);const F=document.createElement("div");F.style.width="350px",F.style.flexGrow="1",F.style.overflow="auto",F.style.marginBottom="10px",F.style.border="1px solid black",F.style.boxSizing="border-box",b.appendChild(F);const w=document.createElement("ul");w.style.height="auto",w.style.fontSize="16px",F.appendChild(w);const N=()=>{w.innerHTML="";for(const e of y){const t=document.createElement("li");t.style.whiteSpace="nowrap";const i=e.webkitRelativePath;t.textContent=i.substring(i.indexOf("/")+1),(e.name.endsWith(".pmx")||e.name.endsWith(".pmd"))&&(t.style.color="blue",t.style.cursor="pointer",t.style.textDecoration="underline",t.onclick=()=>{f=e,u(e)}),w.appendChild(t)}},B=document.createElement("input");B.style.width="100%",B.style.minHeight="80px",B.style.display="block",B.style.backgroundColor="black",B.style.color="white",B.style.marginBottom="10px",B.style.fontSize="20px",B.type="file",B.setAttribute("directory",""),B.setAttribute("webkitdirectory",""),B.setAttribute("allowdirs",""),B.ondragover=e=>{e.preventDefault()},B.ondrop=async e=>{e.preventDefault();const t=e.dataTransfer.items;if(!t)return;const r=[];for(let e=0;e{s.file(e,t)}));""===r.webkitRelativePath&&(Object.defineProperty(r,"webkitRelativePath",{writable:!0}),r.webkitRelativePath=s.fullPath),t.push(r)}return t}(n),N(),s.referenceFiles=y,i.referenceFiles=y},B.onchange=()=>{null!==B.files&&(y=Array.from(B.files),N(),s.referenceFiles=y,i.referenceFiles=y)},b.appendChild(B);const U=document.createElement("div");U.style.width="100%",U.style.height="auto",U.style.display="flex",U.style.flexDirection="row",U.style.justifyContent="space-between",b.appendChild(U);const k=document.createElement("button");k.textContent="Alpha Mode",k.style.flexGrow="1",k.style.height="auto",k.style.border="none",k.style.fontSize="16px",k.style.backgroundColor="#444444",k.style.color="white",k.style.cursor="pointer",k.onclick=()=>{"Alpha Mode"!==m&&(k.style.backgroundColor="#444444",V.style.backgroundColor="#111111",m="Alpha Mode",x(m),X())},U.appendChild(k);const V=document.createElement("button");V.textContent="Force Depth Write Mode",V.style.flexGrow="1",V.style.height="auto",V.style.border="none",V.style.fontSize="16px",V.style.backgroundColor="#111111",V.style.color="white",V.style.cursor="pointer",V.onclick=()=>{"Force Depth Write Mode"!==m&&(k.style.backgroundColor="#111111",V.style.backgroundColor="#444444",m="Force Depth Write Mode",x(m),X())},U.appendChild(V);const G=document.createElement("div");G.textContent="Materials",G.style.width="100%",G.style.height="auto",G.style.fontSize="18px",G.style.backgroundColor="#444444",G.style.color="white",G.style.padding="2px 5px",G.style.boxSizing="border-box",b.appendChild(G);const z=document.createElement("div");z.style.width="350px",z.style.flexGrow="1",z.style.overflow="auto",z.style.marginBottom="10px",z.style.border="1px solid black",z.style.boxSizing="border-box",b.appendChild(z);const W=document.createElement("ol");W.start=0,W.style.height="auto",W.style.fontSize="16px",z.appendChild(W);const X=()=>{if(W.innerHTML="",null===_)return;const e=_.metadata.meshes;for(let i=0;i{null===s.transparencyMode&&(s.transparencyMode=0),s.transparencyMode=(s.transparencyMode+1)%3,g[n]=s.transparencyMode,e.textContent=t(s.transparencyMode??0)},r.appendChild(e)}else{const e=document.createElement("button");e.style.float="right",e.style.width="100px",e.style.height="auto",e.style.fontSize="14px",e.style.marginRight="10px",e.style.border="none",e.textContent=s.transparencyMode===Ws.MATERIAL_OPAQUE?"Opaque":"Alpha Blend";const t=i;e.onclick=()=>{s.transparencyMode=s.transparencyMode===Ws.MATERIAL_OPAQUE?Ws.MATERIAL_ALPHABLEND:Ws.MATERIAL_OPAQUE,p[t]=s.transparencyMode===Ws.MATERIAL_ALPHABLEND,e.textContent=s.transparencyMode===Ws.MATERIAL_OPAQUE?"Opaque":"Alpha Blend"},r.appendChild(e)}W.appendChild(r)}function t(e){switch(e){case Ws.MATERIAL_OPAQUE:return"Opaque";case Ws.MATERIAL_ALPHATEST:return"Alpha Test";case Ws.MATERIAL_ALPHABLEND:return"Alpha Blend";default:return"Unknown"}}},H=document.createElement("div");H.style.width="100%",H.style.height="auto",H.style.display="flex",H.style.flexDirection="column",H.style.justifyContent="center",H.style.alignItems="center",H.style.marginBottom="10px",H.style.border="1px solid black",H.style.padding="20px",H.style.boxSizing="border-box",b.appendChild(H);const K=document.createElement("div");K.style.width="100%",K.style.height="30px",K.style.display="flex",K.style.flexDirection="row",K.style.justifyContent="space-between",K.style.alignItems="center",K.style.marginBottom="10px",H.appendChild(K);const Y=document.createElement("label");Y.textContent="Preserve Serialization Data",Y.title="If enabled, the converted file will be larger, but the converted file will be able to be converted back to PMX without any loss of data in technically(currently BPMX to PMX conversion is not supported).",Y.style.textAlign="left",Y.style.marginRight="10px",Y.style.fontSize="16px",K.appendChild(Y);const q=document.createElement("label");q.textContent="(reload required)",q.style.fontSize="11px",q.style.color="gray",q.style.flexGrow="1",K.appendChild(q);const j=document.createElement("input");j.style.width="16px",j.style.height="16px",j.type="checkbox",j.checked=s.preserveSerializationData,K.appendChild(j),j.onclick=e=>{T?e.preventDefault():(s.preserveSerializationData=j.checked,i.preserveSerializationData=j.checked,null!==f&&u(f))};const Z=document.createElement("div");Z.style.width="100%",Z.style.height="30px",Z.style.display="flex",Z.style.flexDirection="row",Z.style.justifyContent="space-between",Z.style.alignItems="center",Z.style.marginBottom="10px",H.appendChild(Z);const Q=document.createElement("label");Q.textContent="Build Skeleton",Q.title="If your model don't need to be animated by skeleton(e.g. stage model), you can disable this option to reduce the size of the converted file. also, it can improve the performance of the converted model.",Q.style.textAlign="left",Q.style.marginRight="10px",Q.style.fontSize="16px",Q.style.flexGrow="1",Z.appendChild(Q);const $=document.createElement("input");$.style.width="16px",$.style.height="16px",$.type="checkbox",$.checked=s.buildSkeleton,Z.appendChild($);const J=document.createElement("div");J.style.width="100%",J.style.height="30px",J.style.display="flex",J.style.flexDirection="row",J.style.justifyContent="space-between",J.style.alignItems="center",J.style.marginBottom="10px",H.appendChild(J);const ee=document.createElement("label");ee.textContent="Build Morph",ee.title="If your model don't need to be animated by morph targets(e.g. stage model), you can disable this option to reduce the size of the converted file. also, it can improve the performance of the converted model.",ee.style.textAlign="left",ee.style.marginRight="10px",ee.style.fontSize="16px",ee.style.flexGrow="1",J.appendChild(ee);const te=document.createElement("input");te.style.width="16px",te.style.height="16px",te.type="checkbox",te.checked=s.buildMorph,J.appendChild(te);const ie=document.createElement("div");ie.style.width="100%",ie.style.height="auto",ie.style.display="flex",ie.style.flexDirection="row",ie.style.justifyContent="space-between",ie.style.alignItems="center",b.appendChild(ie);const se=document.createElement("button");return se.textContent="Convert",se.style.width="100%",se.style.height="60px",se.style.border="none",se.style.fontSize="20px",ie.appendChild(se),se.onclick=async()=>{if(T)return;if(null===f)return;if(null===_)return;T=!0,t.displayLoadingUI(),t.loadingUIText=`


Converting (${f.name})...`;const e=S.convert(_,{includeSkinningData:$.checked,includeMorphData:te.checked,translucentMaterials:p,alphaEvaluateResults:g}),i=new Blob([e],{type:"application/octet-stream"}),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${f.name.substring(0,f.name.lastIndexOf("."))}.bpmx`,r.click(),URL.revokeObjectURL(s),r.remove(),await new Promise((e=>{setTimeout((()=>{t.hideLoadingUI(),e()}),1500)})),T=!1},C.click(),t.resize(!0),n}}},858:(e,t,i)=>{i.d(t,{y:()=>s});class s{_canvas;_engine;_scene;_onTick;constructor(e){this._canvas=e.canvas,this._engine=e.engine,this._scene=null,this._onTick=null}static async Create(e){const t=new s(e);return t._scene=await t._initialize(e.sceneBuilder),t._onTick=t._makeOnTick(),t}run(){const e=this._engine;window.addEventListener("resize",this._onResize),e.runRenderLoop(this._onTick)}dispose(){window.removeEventListener("resize",this._onResize),this._engine.dispose()}_onResize=()=>{this._engine.resize()};async _initialize(e){return await e.build(this._canvas,this._engine)}_makeOnTick(){const e=this._scene;return()=>e.render()}}},485:(e,t,i)=>{i.a(e,(async(e,t)=>{try{var s=i(67),r=i(858),n=i(535);await new Promise((e=>window.onload=e));const e=document.createElement("canvas");e.style.width="100%",e.style.height="100%",e.style.display="block",document.body.appendChild(e);const a=new s.N(e,!1,{preserveDrawingBuffer:!1,stencil:!0,antialias:!0,alpha:!1,premultipliedAlpha:!1,powerPreference:"high-performance",doNotHandleTouchAction:!0,doNotHandleContextLost:!0,audioEngine:!1,disableWebGL2Support:!1},!0);r.y.Create({canvas:e,engine:a,sceneBuilder:new n.u}).then((e=>e.run())),t()}catch(e){t(e)}}),1)},504:(e,t,i)=>{i.d(t,{n:()=>s});class s{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=s._Counter++}}s._Counter=0},125:(e,t,i)=>{i.d(t,{nO:()=>S,pB:()=>M,M0:()=>b,Iq:()=>P,J:()=>D});class s{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let s=this.line;const r=t.processor;if(r){r.lineProcessor&&(s=r.lineProcessor(s,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";!t.isFragment&&r.attributeProcessor&&this.line.startsWith(i)?s=r.attributeProcessor(this.line,e,t.processingContext):r.varyingProcessor&&(r.varyingCheck?.(this.line,t.isFragment)||!r.varyingCheck&&this.line.startsWith(n))?s=r.varyingProcessor(this.line,t.isFragment,e,t.processingContext):r.uniformProcessor&&r.uniformRegexp&&r.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&r.uniformBufferRegexp&&r.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):r.textureProcessor&&r.textureRegexp&&r.textureRegexp.test(this.line)?s=r.textureProcessor(this.line,t.isFragment,e,t.processingContext):(r.uniformProcessor||r.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?r.uniformProcessor&&(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r.endOfUniformBufferProcessor&&(s=r.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=s+"\n"}return this.children.forEach((s=>{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class r{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{c=c.trim(),""!==c&&(i.push(c),c="")},n=e=>{so._Stack[s],h=()=>-1===s?"!!INVALID EXPRESSION!!":o._Stack[s--];let l=0,c="";for(;l1){for(r();-1!==s&&o._OperatorPriority[a()]>=o._OperatorPriority[d];)i.push(h());n(d),l++}else c+=t;l++}for(r();-1!==s;)"("===a()?h():i.push(h());return o._InfixToPostfixCache.size>=o.InfixToPostfixCacheLimitSize&&o.ClearCache(),o._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(o._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var u=i(503),f=i(662),_=i(741);const p=/defined\s*?\((.+?)\)/g,g=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,T=/__decl__/,x=/light\{X\}.(\w*)/g,E=/\{X\}/g,v=[],A=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function M(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function b(e,t,i,n){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),P(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const a=function(e,t,i){let n=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return n;if(t.processor.shaderLanguage===f.w.GLSL&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const a=t.defines,o=function(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===f.w.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",(0,_.xt)(s,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),s}(t,i);return t.processor.preProcessor&&(n=t.processor.preProcessor(n,a,o,t.isFragment,t.processingContext)),n=function(e,t,i){const n=new s,a=new r;return a.lineIndex=-1,a.lines=e.split("\n"),C(a,n),n.process(t,i)}(n,o,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}(e,t,n);i(a,e)}))}function S(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function y(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new h(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new h(e);const n=e.substring(0,r).trim(),a=e.substring(r+s.length).trim();return new d(n,s,a)}function I(e,t){const i=new a,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new h(r):"#ifndef"===s?new h(r,!0):function(e){e=e.replace(p,"defined[$1]");const t=o.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new c:new l;"string"==typeof t&&(t=t.replace(g,"defined($1)")),"string"==typeof s&&(s=s.replace(g,"defined($1)")),r.leftOperand="string"==typeof s?y(s):s,r.rightOperand="string"==typeof t?y(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(g,"defined($1)")),"string"==typeof s?y(s):s}(r),i}function R(e,t,i){let r=e.currentLine;for(;C(e,i);){r=e.currentLine;const n=r.substring(0,5).toLowerCase();if("#else"===n){const i=new s;return t.children.push(i),void C(e,i)}if("#elif"===n){const e=I(r,5);t.children.push(e),i=e}}}function C(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=A.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new n;t.children.push(s);const r=I(i,6);s.children.push(r),R(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new n;t.children.push(s);const r=I(i,7);s.children.push(r),R(e,s,r);break}case"#if":{const s=new n,r=I(i,3);t.children.push(s),s.children.push(r),R(e,s,r);break}}continue}}const r=new s;if(r.line=i,t.children.push(r),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");r.additionalDefineKey=e[1],3===e.length&&(r.additionalDefineValue=e[2])}}return!1}function P(e,t,i){let s;for(v.length=0;null!==(s=m.exec(e));)v.push(s);let r=String(e),n=[e],a=!1;for(const e of v){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(T,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void D.loadFile(e,(e=>{t.includesShadersStore[s]=e,P(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=a.replace(E,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(x,((e,t)=>t+"{X}"))),i=i.replace(E,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}v.length=0,r=n.join(""),a?P(r.toString(),t,i):i(r)}const D={loadFile:(e,t,i,s,r,n)=>{throw(0,u.n)("FileTools")}}},716:(e,t,i)=>{i.d(t,{d:()=>s});class s{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},741:(e,t,i)=>{i.d(t,{W0:()=>a,iL:()=>n,sg:()=>r,xt:()=>o});var s=i(503);i(790);const r={};function n(e,t,i=""){return i+(t?t+"\n":"")+e}function a(e,t,i,n,a,o,h){const l=h||r.loadFile;if(l)return l(e,t,i,n,a,o);throw(0,s.n)("FileTools")}function o(e,t,i,s){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(s?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),s&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}},326:(e,t,i)=>{i.d(t,{$:()=>T,r:()=>m});var s=i(315),r=i(137),n=i(420),a=i(215),o=i(237);class h{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class l{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class c{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=c.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=c.KEEP,this.opDepthFail=c.KEEP,this.opStencilDepthPass=c.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}c.ALWAYS=519,c.KEEP=7680,c.REPLACE=7681;class d{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,s){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===s||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=s,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,s){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===s||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=s,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}var u=i(503),f=i(854),_=i(790),p=i(848),g=i(741);function m(e,t){if((0,_.BA)()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}class T{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,this._depthCullingState.depthFunc=e?518: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)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_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()}n.M.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){r.V.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,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,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)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,(0,_.BA)()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)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;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_queueNewFrame(e,t){return m(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),1===this._activeRenderLoops.length&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}getHostWindow(){return(0,_.BA)()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}get currentViewport(){return this._cachedViewport}setViewport(e,t,i){const s=t||this.getRenderWidth(),r=i||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*s,a*r,s*e.width,r*e.height)}createCanvasImage(){return document.createElement("img")}get description(){let e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}_createTextureBase(e,t,i,n,a=3,o=null,h=null,l,c,d=null,u=null,_=null,p=null,g,m,x){const E="data:"===(e=e||"").substr(0,5),v="blob:"===e.substr(0,5),A=E&&-1!==e.indexOf(";base64,"),M=u||new f.h(this,f.G.Url);M!==u&&(M.label=e.substring(0,60));const b=e;!this._transformTextureUrl||A||u||d||(e=this._transformTextureUrl(e)),b!==e&&(M._originalUrl=b);const S=e.lastIndexOf(".");let y=p||(S>-1?e.substring(S).toLowerCase():""),I=null;y.indexOf("?")>-1&&(y=y.split("?")[0]);for(const e of T._TextureLoaders)if(e.canLoad(y,g)){I=e;break}n&&n.addPendingData(M),M.url=e,M.generateMipMaps=!t,M.samplingMode=a,M.invertY=i,M._useSRGBBuffer=this._getUseSRGBBuffer(!!x,t),this._doNotHandleContextLost||(M._buffer=d);let R=null;o&&!u&&(R=M.onLoadedObservable.add(o)),u||this._internalTexturesCache.push(M);const C=(i,u)=>{n&&n.removePendingData(M),e===b?(R&&M.onLoadedObservable.remove(R),s.q.UseFallbackTexture&&e!==s.q.FallbackTexture&&this._createTextureBase(s.q.FallbackTexture,t,M.invertY,n,a,null,h,l,c,d,M),i=(i||"Unknown error")+(s.q.UseFallbackTexture?" - Fallback texture was used":""),M.onErrorObservable.notifyObservers({message:i,exception:u}),h&&h(i,u)):(r.V.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,M.invertY,n,a,o,h,l,c,d,M,_,p,g,m,x))};if(I){const t=e=>{I.loadData(e,M,((e,t,i,s,r,o)=>{o?C("TextureLoader failed to load data"):l(M,y,n,{width:e,height:t},M.invertY,!i,s,(()=>(r(),!1)),a)}),m)};d?d instanceof ArrayBuffer?t(new Uint8Array(d)):ArrayBuffer.isView(d)?t(d):h&&h("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,n?n.offlineProvider:void 0,!0,((e,t)=>{C("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{v&&!this._doNotHandleContextLost&&(M._buffer=e),l(M,y,n,e,M.invertY,t,!1,c,a)};!E||A?d&&("string"==typeof d.decoding||d.close)?i(d):T._FileToolsLoadImage(e||"",i,C,n?n.offlineProvider:null,g,M.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof d||d instanceof ArrayBuffer||ArrayBuffer.isView(d)||d instanceof Blob?T._FileToolsLoadImage(d,i,C,n?n.offlineProvider:null,g,M.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):d&&i(d)}return M}_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:(0,_.Nf)()?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.7.0"}static get Version(){return"7.7.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){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new h,this._stencilStateComposer=new l,this._stencilState=new c,this._alphaState=new d,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 p.cP,this.onCanvasFocusObservable=new p.cP,this.onNewSceneAddedObservable=new p.cP,this.onResizeObservable=new p.cP,this.onCanvasPointerOutObservable=new p.cP,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 p.cP,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new p.cP,this.onAfterShaderCompilationObservable=new p.cP,this.onBeginFrameObservable=new p.cP,this.onEndFrameObservable=new p.cP,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new p.cP,this.onContextRestoredObservable=new p.cP,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 p.cP,s.q.Instances.push(this),this.startTime=o.j.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,a.I.SetMatrixPrecision(!!t.useHighPrecisionMatrix),(0,_.XD)()&&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??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const r=(0,_.BA)()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||r;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,r):1,this._lastDevicePixelRatio=r,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=(0,_.BA)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,_.BA)()&&(0,_.Nf)())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.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)return!1;if(e|=0,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 e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,_.Nf)()&&"ontouchend"in document},this._checkForMobile(),(0,_.BA)()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_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("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return T._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n){throw(0,u.n)("FileTools")}_loadFile(e,t,i,s,r,n){const a=(0,g.W0)(e,t,i,s,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(a);-1!==e&&this._activeRequests.splice(e,1)})),a}static _FileToolsLoadFile(e,t,i,s,r,n){if(g.sg.loadFile)return g.sg.loadFile(e,t,i,s,r,n);throw(0,u.n)("FileTools")}dispose(){for(this.hideLoadingUI(),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();this.releaseComputeEffects?.(),n.M.ResetCache();for(const e of this._activeRequests)e.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(),(0,_.BA)()&&window.removeEventListener("resize",this._checkForMobile);const e=s.q.Instances.indexOf(this);e>=0&&s.q.Instances.splice(e,1),s.q.Instances.length||s.q.OnEnginesDisposedObservable.notifyObservers(this),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw(0,u.n)("LoadingScreen")}}T._TextureLoaders=[],T._RenderPassIdCounter=0,T._RescalePostProcessFactory=null},67:(e,t,i)=>{i.d(t,{N:()=>T});var s=i(854),r=i(315),n=i(321),a=i(237);class o{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new h(e)}sampleFrame(e=a.j.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){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 0===e?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 h{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-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}}var l=i(329),c=i(137),d=i(716);n.w.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){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: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 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 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}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},n.w.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,a=!0,o=!1,h=0,l=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let d=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return o?n||(n=function(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}(e.type,4*t*i)):d===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),d=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),d=c.FLOAT),a&&this.flushFramebuffer(),c.readPixels(h,l,t,i,c.RGBA,d,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},n.w.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,a=!0,o=!1,h=0,l=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,a,o,h,l))},n.w.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},n.w.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};var u=i(790),f=i(326);function _(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}f.$.prototype.displayLoadingUI=function(){if(!(0,u.BA)())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},f.$.prototype.hideLoadingUI=function(){if(!(0,u.BA)())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(f.$.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=f.$.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(f.$.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(f.$.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),f.$.prototype.getInputElement=function(){return this._renderingCanvas},f.$.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},f.$.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},f.$.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},f.$.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},f.$.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},f.$.prototype.getInputElement=function(){return this._renderingCanvas},f.$.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},f.$.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},f.$.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},f.$.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},f.$.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},f.$.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},f.$.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},f.$.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},f.$.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},f.$.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},f.$.prototype.getStencilMask=function(){return this._stencilState.stencilMask},f.$.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},f.$.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},f.$.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},f.$.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},f.$.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},f.$.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},f.$.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},f.$.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},f.$.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},f.$.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},f.$.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},f.$.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},f.$.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},f.$.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},f.$.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},f.$.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},f.$.prototype.getAlphaMode=function(){return this._alphaMode},f.$.prototype.getAlphaEquation=function(){return this._alphaEquation},f.$.prototype.getRenderPassNames=function(){return this._renderPassNames},f.$.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},f.$.prototype.createRenderPassId=function(e){const t=++f.$._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},f.$.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;tnew m(e,t,i);class m{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 g.cP,this.onAudioLockedObservable=new g.cP,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,u.BA)())return;void 0!==window.AudioContext&&(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(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContext(){return this._audioContext?.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,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,c.V.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 e=".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) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),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 T extends n.w{static get NpmPackage(){return f.$.NpmPackage}static get Version(){return f.$.Version}static get Instances(){return r.q.Instances}static get LastCreatedEngine(){return r.q.LastCreatedEngine}static get LastCreatedScene(){return r.q.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const s=e.getHostWindow();s&&"function"==typeof s.addEventListener&&(s.addEventListener("blur",e._onBlur),s.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!f.$.audioEngine&&i.audioEngine&&f.$.AudioEngineFactory&&(f.$.audioEngine=f.$.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),(0,u.Nf)()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&_(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==f.$.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return function(e,t,i,s){const r=e.createCanvas(i,s).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,i,s).data}(this,e,t,i)}_createImageBitmapFromSource(e,t){return function(e,t,i){return new Promise(((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{s(e)}))}))},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t}))}(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&function(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&function(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}()}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){const i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}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 r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_loadFileAsync(e,t,i){return new Promise(((s,r)=>{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))}setTextureFromPostProcess(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)}setTextureFromPostProcessOutput(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return function(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}(e)}_renderFrame(){for(let e=0;e0&&0===this._frameHandler&&(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()))}_renderViews(){return!1}enterPointerlock(){this._renderingCanvas&&_(this._renderingCanvas)}exitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}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,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,s,r){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 n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&T._RescalePostProcessFactory&&(this._rescalePostProcess=T._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}wrapWebGLTexture(e,t=!1,i=3,r=0,n=0){const a=new d.d(e,this._gl),o=new s.h(this,s.G.Unknown,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=n,o.width=r,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let l=r.TEXTURE_2D;e.isCube&&(l=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(l,s,o,a,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void c.V.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(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),0===t?(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 l.A(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const a=()=>{const o=s.clientWaitSync(e,t,0);o!=s.WAIT_FAILED?o!=s.TIMEOUT_EXPIRED?r():setTimeout(a,i):n()};a()}))}_readPixelsAsync(e,t,i,s,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const o=this._gl,h=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,s,r,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const l=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return l?(o.flush(),this._clientWaitAsync(l,0,10).then((()=>(o.deleteSync(l),o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(h),a)))):null}dispose(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),function(e,t){1===r.q.Instances.length&&f.$.audioEngine&&(f.$.audioEngine.dispose(),f.$.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),(0,u.Nf)()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}(this,this._renderingCanvas),super.dispose()}}T.ALPHA_DISABLE=0,T.ALPHA_ADD=1,T.ALPHA_COMBINE=2,T.ALPHA_SUBTRACT=3,T.ALPHA_MULTIPLY=4,T.ALPHA_MAXIMIZED=5,T.ALPHA_ONEONE=6,T.ALPHA_PREMULTIPLIED=7,T.ALPHA_PREMULTIPLIED_PORTERDUFF=8,T.ALPHA_INTERPOLATE=9,T.ALPHA_SCREENMODE=10,T.DELAYLOADSTATE_NONE=0,T.DELAYLOADSTATE_LOADED=1,T.DELAYLOADSTATE_LOADING=2,T.DELAYLOADSTATE_NOTLOADED=4,T.NEVER=512,T.ALWAYS=519,T.LESS=513,T.EQUAL=514,T.LEQUAL=515,T.GREATER=516,T.GEQUAL=518,T.NOTEQUAL=517,T.KEEP=7680,T.REPLACE=7681,T.INCR=7682,T.DECR=7683,T.INVERT=5386,T.INCR_WRAP=34055,T.DECR_WRAP=34056,T.TEXTURE_CLAMP_ADDRESSMODE=0,T.TEXTURE_WRAP_ADDRESSMODE=1,T.TEXTURE_MIRROR_ADDRESSMODE=2,T.TEXTUREFORMAT_ALPHA=0,T.TEXTUREFORMAT_LUMINANCE=1,T.TEXTUREFORMAT_LUMINANCE_ALPHA=2,T.TEXTUREFORMAT_RGB=4,T.TEXTUREFORMAT_RGBA=5,T.TEXTUREFORMAT_RED=6,T.TEXTUREFORMAT_R=6,T.TEXTUREFORMAT_RG=7,T.TEXTUREFORMAT_RED_INTEGER=8,T.TEXTUREFORMAT_R_INTEGER=8,T.TEXTUREFORMAT_RG_INTEGER=9,T.TEXTUREFORMAT_RGB_INTEGER=10,T.TEXTUREFORMAT_RGBA_INTEGER=11,T.TEXTURETYPE_UNSIGNED_BYTE=0,T.TEXTURETYPE_UNSIGNED_INT=0,T.TEXTURETYPE_FLOAT=1,T.TEXTURETYPE_HALF_FLOAT=2,T.TEXTURETYPE_BYTE=3,T.TEXTURETYPE_SHORT=4,T.TEXTURETYPE_UNSIGNED_SHORT=5,T.TEXTURETYPE_INT=6,T.TEXTURETYPE_UNSIGNED_INTEGER=7,T.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,T.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,T.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,T.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,T.TEXTURETYPE_UNSIGNED_INT_24_8=12,T.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,T.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,T.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,T.TEXTURE_NEAREST_SAMPLINGMODE=1,T.TEXTURE_BILINEAR_SAMPLINGMODE=2,T.TEXTURE_TRILINEAR_SAMPLINGMODE=3,T.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,T.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,T.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,T.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,T.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,T.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,T.TEXTURE_NEAREST_LINEAR=7,T.TEXTURE_NEAREST_NEAREST=1,T.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,T.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,T.TEXTURE_LINEAR_LINEAR=2,T.TEXTURE_LINEAR_NEAREST=12,T.TEXTURE_EXPLICIT_MODE=0,T.TEXTURE_SPHERICAL_MODE=1,T.TEXTURE_PLANAR_MODE=2,T.TEXTURE_CUBIC_MODE=3,T.TEXTURE_PROJECTION_MODE=4,T.TEXTURE_SKYBOX_MODE=5,T.TEXTURE_INVCUBIC_MODE=6,T.TEXTURE_EQUIRECTANGULAR_MODE=7,T.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,T.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,T.SCALEMODE_FLOOR=1,T.SCALEMODE_NEAREST=2,T.SCALEMODE_CEILING=3},315:(e,t,i)=>{i.d(t,{q:()=>r});var s=i(848);class r{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}r.Instances=[],r.OnEnginesDisposedObservable=new s.cP,r._LastCreatedScene=null,r.UseFallbackTexture=!0,r.FallbackTexture=""},215:(e,t,i)=>{i.d(t,{I:()=>s});class s{static SetMatrixPrecision(e){if(s.MatrixTrackPrecisionChange=!1,e&&!s.MatrixUse64Bits&&s.MatrixTrackedMatrices)for(let e=0;e{i.d(t,{l:()=>r});var s=i(662);class r{static GetShadersRepository(e=s.w.GLSL){return e===s.w.GLSL?r.ShadersRepository:r.ShadersRepositoryWGSL}static GetShadersStore(e=s.w.GLSL){return e===s.w.GLSL?r.ShadersStore:r.ShadersStoreWGSL}static GetIncludesShadersStore(e=s.w.GLSL){return e===s.w.GLSL?r.IncludesShadersStore:r.IncludesShadersStoreWGSL}}r.ShadersRepository="src/Shaders/",r.ShadersStore={},r.IncludesShadersStore={},r.ShadersRepositoryWGSL="src/ShadersWGSL/",r.ShadersStoreWGSL={},r.IncludesShadersStoreWGSL={}},852:(e,t,i)=>{i.d(t,{tI:()=>u,bS:()=>T,tg:()=>f,YM:()=>_,C5:()=>m,GX:()=>d,kf:()=>l,EX:()=>c,Cm:()=>h,N5:()=>o});class s{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))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,r,n,a,o){const h=this.engine;if(h.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let l;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,l=0;l{n[e]=t}));for(const e of h.getAttributes(this,a))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==s&&(n[2]=s,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.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];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}var r=i(741);const n=new WeakMap,a={_webGLVersion:2,cachedPipelines:{}};function o(e){let t=n.get(e);if(!t){if(!e)return a;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},n.set(e,t)}return t}function h(e){n.delete(e)}function l(e,t,i,s,r,n){const a=o(s);return n||(n=a._createShaderProgramInjection??u),n(e,g(t,"vertex",s,a._contextWasLost),g(i,"fragment",s,a._contextWasLost),s,r,a.validateShaderPrograms)}function c(e,t,i,s,r,n=null,a){const h=o(r);a||(a=h._createShaderProgramInjection??u);const l=h._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return a(e,p(t,"vertex",s,l,r,h._contextWasLost),p(i,"fragment",s,l,r,h._contextWasLost),r,n,h.validateShaderPrograms)}function d(e,t){const i=new s,r=o(e);return r.parallelShaderCompile&&(i.isParallelCompiled=!0),i.context=r._context,i}function u(e,t,i,s,r=null,n){const a=s.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return s.attachShader(a,t),s.attachShader(a,i),s.linkProgram(a),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||f(e,s,n),a}function f(e,t,i){const s=e.context,r=e.vertexShader,n=e.fragmentShader,a=e.program;if(!s.getProgramParameter(a,s.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=s.getProgramInfoLog(a);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(s.validateProgram(a),!s.getProgramParameter(a,s.VALIDATE_STATUS))){const t=s.getProgramInfoLog(a);if(t)throw e.programValidationError=t,new Error(t)}s.deleteShader(r),s.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function _(e,t,i,s,r,n,a,h,d,u="",f,_){const p=o(e.context);f||(f=p.createRawShaderProgramInjection??l),_||(_=p.createShaderProgramInjection??c);const g=e;g.program=s?f(g,t,i,g.context,d):_(g,t,i,h,g.context,d),g.program.__SPECTOR_rebuildProgram=a}function p(e,t,i,s,n,a){return g((0,r.iL)(e,i,s),t,n,a)}function g(e,t,i,s){const r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${s}`)}return i.shaderSource(r,e),i.compileShader(r),r}function m(e,t){t.useProgram(e)}function T(e,t){const i=e;if(!i.isParallelCompiled)return void t(e);const s=i.onCompiled;i.onCompiled=()=>{s?.(),t(e)}}},321:(e,t,i)=>{i.d(t,{w:()=>E});var s=i(852),r=i(137),n=i(790),a=i(662);class o{constructor(){this.shaderLanguage=a.w.GLSL}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const h=/(flat\s)?\s*varying\s*.*/;class l{constructor(){this.shaderLanguage=a.w.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return h.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}var c=i(329),d=i(597),u=i(326),f=i(716),_=i(854),p=i(420),g=i(503),m=i(741),T=i(647);class x{}class E extends u.${get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return p.M.ShadersRepository}static set ShadersRepository(e){p.M.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!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,n){if(i=i||{},super(t??i.antialias,i,n),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 a=null;if(e.getContext){if(a=e,this._renderingCanvas=a,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of E.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,r.V.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},a.addEventListener("webglcontextlost",this._onContextLost,!1),a.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=a.getContext("webgl2",i)||a.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!a)throw new Error("The provided canvas is null or undefined.");try{this._gl=a.getContext("webgl",i)||a.getContext("experimental-webgl",i)}catch(e){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 t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new l:new o;const h=`Babylon.js v${E.Version}`;r.V.Log(h+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",h);const c=(0,s.N5)(this._gl);c.validateShaderPrograms=this.validateShaderPrograms,c.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(){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||null!==this._gl.getExtension("OES_standard_derivatives"),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||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),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:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(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"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.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 e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,a){const o=this._currentBufferPointers[t];if(!o)return;let h=!1;o.active?(o.buffer!==e&&(o.buffer=e,h=!0),o.size!==i&&(o.size=i,h=!0),o.type!==s&&(o.type=s,h=!0),o.normalized!==r&&(o.normalized=r,h=!0),o.stride!==n&&(o.stride=n,h=!0),o.offset!==a&&(o.offset=a,h=!0)):(h=!0,o.active=!0,o.index=t,o.size=i,o.type=s,o.normalized=r,o.stride=n,o.offset=a,o.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,a):this._gl.vertexAttribPointer(t,i,s,r,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let a=null;if(i&&(a=i[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const o=a.getBuffer();o&&(this._vertexAttribPointer(o,n,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[a],this._gl.FLOAT,!1,s,n)),n+=4*i[a]}}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)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(h=1),1!==o||this._caps.textureFloat||(o=0,r.V.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,f=new _.h(this,s),p=e.width||e,g=e.height||e,m=e.depth||0,T=e.layers||0,x=this._getSamplingParameters(h,a),E=0!==T?u.TEXTURE_2D_ARRAY:0!==m?u.TEXTURE_3D:u.TEXTURE_2D,v=this._getRGBABufferInternalSizedFormat(o,l,c),A=this._getInternalFormat(l),M=this._getWebGLTextureType(o);return this._bindTextureDirectly(E,f),0!==T?(f.is2DArray=!0,u.texImage3D(E,0,v,p,g,T,0,A,M,null)):0!==m?(f.is3D=!0,u.texImage3D(E,0,v,p,g,m,0,A,M,null)):u.texImage2D(E,0,v,p,g,0,A,M,null),u.texParameteri(E,u.TEXTURE_MAG_FILTER,x.mag),u.texParameteri(E,u.TEXTURE_MIN_FILTER,x.min),u.texParameteri(E,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(E,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(E),this._bindTextureDirectly(E,null),f._useSRGBBuffer=c,f.baseWidth=p,f.baseHeight=g,f.width=p,f.height=g,f.depth=T,f.isReady=!0,f.samples=d,f.generateMipMaps=a,f.samplingMode=h,f.type=o,f.format=l,f.label=n,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,a=null,o=null,h=null,l=null,c=null,d,u,f,p){return this._createTextureBase(e,t,i,s,r,n,a,((...e)=>this._prepareWebGLTexture(...e,l)),((e,t,i,r,n,a)=>{const o=this._gl,h=i.width===e&&i.height===t;n._creationFlags=f??0;const l=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(h)return o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new _.h(this,_.G.Temp);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,i),this._rescaleTexture(e,n,s,l.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,n,!0),a()}))}return!0}),o,h,l,c,d,u,p)}_getTexImageParametersForCreateTexture(e,t){let i,s;return 1===this.webGLVersion?(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,r){}createRawTexture(e,t,i,s,r,n,a,o=null,h=0,l=0,c=!1){throw(0,g.n)("Engine.RawTexture")}createRawCubeTexture(e,t,i,s,r,n,a,o=null){throw(0,g.n)("Engine.RawTexture")}createRawTexture3D(e,t,i,s,r,n,a,o,h=null,l=0){throw(0,g.n)("Engine.RawTexture")}createRawTexture2DArray(e,t,i,s,r,n,a,o,h=null,l=0){throw(0,g.n)("Engine.RawTexture")}createPrefilteredCubeTexture(e,t,i,s,r,n,a,o,h){throw(0,g.n)("Misc/dds")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_setupDepthStencilTexture(e,t,i,s,r,n=1){const a=t.width||t,o=t.height||t,h=t.layers||0,l=t.depth||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=h>0,e.depth=h||l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,d=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(d,c.TEXTURE_MAG_FILTER,u.mag),c.texParameteri(d,c.TEXTURE_MIN_FILTER,u.min),c.texParameteri(d,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(d,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(d,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(d,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(d,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(d,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,a=0){const o=this._gl;let h=o.TEXTURE_2D;if(e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(h,a,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),l=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),u=Math.round(Math.log(e.height)*Math.LOG2E),f=n?e.width:Math.pow(2,Math.max(d-s,0)),_=n?e.height:Math.pow(2,Math.max(u-s,0));a.texImage2D(c,s,l,f,_,0,h,o,t)}updateTextureData(e,t,i,s,r,n,a=0,o=0,h=!1){const l=this._gl,c=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let u=l.TEXTURE_2D,f=l.TEXTURE_2D;e.isCube&&(f=l.TEXTURE_CUBE_MAP_POSITIVE_X+a,u=l.TEXTURE_CUBE_MAP),this._bindTextureDirectly(u,e,!0),l.texSubImage2D(f,o,i,s,r,n,d,c,t),h&&this._gl.generateMipmap(f),this._bindTextureDirectly(u,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const a=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,a,o,h,l){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?(0,d.R)(s.width,c):s.width),f=Math.min(c,this.needPOTTextures?(0,d.R)(s.height,c):s.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=f,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:l??(".jpg"!==t||e._useSRGBBuffer?5:4),o(u,f,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,a,h)}))||this._prepareWebGLTextureContinuation(e,i,n,a,h)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,i,s,r,n,a)}_updateRenderBuffer(e,t,i,s,r,n,a,o=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),s>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,s,n,t,i):h.renderbufferStorage(h.RENDERBUFFER,r,t,i),h.framebufferRenderbuffer(h.FRAMEBUFFER,a,h.RENDERBUFFER,e),o&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&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&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&((0,s.C5)(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw r.V.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(n=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_bindTexture(e,t,i){if(void 0===e)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){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(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 i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(o,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(o,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},(0,n.BA)()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),(0,s.Cm)(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 r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}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}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;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;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;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;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;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:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,r=!0,n=!0){const a=r?4:3,o=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*a);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,o,this._gl.UNSIGNED_BYTE,h),Promise.resolve(h)}generateMipMapsForCubemap(e,t){}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}E._TempClearColorUint32=new Uint32Array(4),E._TempClearColorInt32=new Int32Array(4),E.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"]}],E.CollisionsEpsilon=.001,E._ConcatenateShader=m.iL,E._IsSupported=null,E._HasMajorPerformanceCaveat=null,E.CeilingPOT=d.Tg,E.FloorPOT=d.C4,E.NearestPOT=d.OG,E.GetExponentOfTwo=d.R,E.QueueNewFrame=u.r},854:(e,t,i)=>{i.d(t,{h:()=>a,G:()=>s});var s,r=i(848);class n{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,r=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=r,this._comparisonFunction=n,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}}!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth"}(s||(s={}));class a extends n{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 r.cP,this.onErrorObservable=new r.cP,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=s.Unknown,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._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._engine=e,this._source=t,this._uniqueId=a._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(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case s.Temp:break;case s.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case s.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case s.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case s.Cube:return void(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));case s.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case s.CubeRawRGBD:return;case s.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case s.DepthStencil:case s.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.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);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}a._Counter=0},647:(e,t,i)=>{i.d(t,{b4:()=>c,bu:()=>u,mO:()=>d,uR:()=>_});var s=i(790),r=i(662),n=i(852),a=i(610),o=i(137),h=i(125),l=i(741);function c(e,t){return(0,n.N5)(t).cachedPipelines[e]}function d(e){const t=e._name,i=e.context;if(t&&i){const e=(0,n.N5)(i),s=e.cachedPipelines[t];s?.dispose(),delete e.cachedPipelines[t]}}function u(e,t,i,n,a,o,l){let c,d;const u=(0,s.BA)()?o?.getHostDocument():null;c="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?u?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,d="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?u?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const _=[void 0,void 0],p=()=>{if(_[0]&&_[1]){e.isFragment=!0;const[s,c]=_;(0,h.M0)(c,e,((o,c)=>{l&&(l._fragmentSourceCodeBeforeMigration=c),i&&(o=i("fragment",o));const d=(0,h.nO)(s,o,e);e=null;const u=function(e,t,i,s){if(i){const n=i.vertexElement||i.vertex||i.spectorName||i,a=i.fragmentElement||i.fragment||i.spectorName||i;return{vertexSourceCode:(s===r.w.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,fragmentSourceCode:(s===r.w.WGSL?"//":"")+"#define SHADER_NAME fragment:"+a+"\n"+t}}return{vertexSourceCode:e,fragmentSourceCode:t}}(d.vertexCode,d.fragmentCode,t,a);n?.(u.vertexSourceCode,u.fragmentSourceCode)}),o)}};f(c,"Vertex","",(t=>{(0,h.pB)(e),(0,h.M0)(t,e,((e,s)=>{l&&(l._rawVertexSourceCode=t,l._vertexSourceCodeBeforeMigration=s),i&&(e=i("vertex",e)),_[0]=e,p()}),o)}),a),f(d,"Fragment","Pixel",(e=>{l&&(l._rawFragmentSourceCode=e),_[1]=e,p()}),a)}function f(e,t,i,r,n,o){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void r((0,s.Zl)(e));if("source:"===e.substr(0,7))return void r(e.substr(7));if("base64:"===e.substr(0,7))return void r(window.atob(e.substr(7)));const h=a.l.GetShadersStore(n);if(h[e+t+"Shader"])return void r(h[e+t+"Shader"]);if(i&&h[e+i+"Shader"])return void r(h[e+i+"Shader"]);let c;if(c="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:a.l.GetShadersRepository(n)+e,!(o=o||l.W0))throw new Error("loadFileInjection is not defined");o(c+"."+t.toLowerCase()+".fx",r)}const _=(e,t,i,s)=>{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&((0,n.N5)(e.context).cachedPipelines[e.name]=r),i(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),s(r,(()=>{e.onRenderingStateCompiled?.(r)})),r}catch(e){throw o.V.Error("Error compiling effect"),e}}},420:(e,t,i)=>{i.d(t,{M:()=>h});var s=i(848),r=i(137),n=i(610),a=i(662),o=i(647);class h{static get ShadersRepository(){return n.l.ShadersRepository}static set ShadersRepository(e){n.l.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new s.cP),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r=null,n,l=null,c=null,d=null,u=null,f,_="",p=a.w.GLSL){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new s.cP,this.onErrorObservable=new s.cP,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=_;const g=this._key.replace(/\r/g,"").replace(/\n/g,"|");let m;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??a.w.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}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){this.isReady()?e(this):(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){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??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=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,s),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:a._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},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(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&2===n.length){const t=parseInt(n[1]),s=e.split("\n",-1);s.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(r.V.Error("Unable to compile effect:"),r.V.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),r.V.Error("Attributes: "+i.map((function(e){return" "+e}))),r.V.Error("Defines:\n"+this.defines),h.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(r.V.Error("Vertex code:"),r.V.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(r.V.Error("Fragment code:"),r.V.Error(i))),e&&r.V.Error(e),t&&r.V.Error(t)}r.V.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,r.V.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)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{var s;i.d(t,{w:()=>s}),function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(s||(s={}))},329:(e,t,i)=>{i.d(t,{A:()=>r});var s=i(504);class r extends s.n{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},503:(e,t,i)=>{i.d(t,{n:()=>r});const s={};function r(e,t=!1){if(!t||!s[e])return s[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}},790:(e,t,i)=>{function s(){return"undefined"!=typeof window}function r(){return"undefined"!=typeof navigator}function n(){return"undefined"!=typeof document}function a(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}i.d(t,{BA:()=>s,Nf:()=>n,XD:()=>r,Zl:()=>a})},137:(e,t,i)=>{i.d(t,{V:()=>s});class s{static _CheckLimit(e,t){let i=s._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},s._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=s._LogLimitOutputs[e];if(!i||!s.MessageLimitReached)return;const r=this._Levels[t];i.current===i.limit&&s[r.name](s.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,r.name??""))}static _AddLogEntry(e){s._LogCache=e+s._LogCache,s.OnNewCacheEntry&&s.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const r=Array.isArray(t)?t[0]:t;if(void 0!==i&&!s._CheckLimit(r,i))return;const n=s._FormatMessage(r),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+n,...o);const h=`
${n}

`;s._AddLogEntry(h),s._GenerateLimitMessage(r,e)}static get LogCache(){return s._LogCache}static ClearLogCache(){s._LogCache="",s._LogLimitOutputs={},s.errorsCount=0}static set LogLevels(e){s.Log=s._LogDisabled,s.Warn=s._LogDisabled,s.Error=s._LogDisabled,[s.MessageLogLevel,s.WarningLogLevel,s.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];s[e.name]=s._LogEnabled.bind(s,t)}}))}}s.NoneLogLevel=0,s.MessageLogLevel=1,s.WarningLogLevel=2,s.ErrorLogLevel=4,s.AllLogLevel=7,s.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",s._LogCache="",s._LogLimitOutputs={},s._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],s.errorsCount=0,s.Log=s._LogEnabled.bind(s,s.MessageLogLevel),s.Warn=s._LogEnabled.bind(s,s.WarningLogLevel),s.Error=s._LogEnabled.bind(s,s.ErrorLogLevel)},848:(e,t,i)=>{i.d(t,{cP:()=>n});class s{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 r{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 n{static FromPromise(e,t){const i=new n;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),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 s(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,n=!1){if(!e)return null;const a=new r(e,t,s);return a.unregisterOnNextCall=n,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}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-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new n;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}}},296:(e,t,i)=>{i.d(t,{A:()=>r});var s=i(237);class r{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){r.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){r.Enabled&&(this._startMonitoringTime=s.j.Now)}endMonitoring(e=!0){if(!r.Enabled)return;e&&this.fetchNewFrame();const t=s.j.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=s.j.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}r.Enabled=!0},237:(e,t,i)=>{i.d(t,{j:()=>r});var s=i(790);class r{static get Now(){return(0,s.BA)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},597:(e,t,i)=>{function s(e){let t=1;do{t*=2}while(te-i?i:t}function a(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function o(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function h(e,t,i=2){let s;switch(i){case 1:s=o(e);break;case 2:s=n(e);break;default:s=a(e)}return Math.min(s,t)}i.d(t,{C4:()=>o,L8:()=>s,OG:()=>n,R:()=>h,Tg:()=>a,zF:()=>r})}},n={};function a(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e](i,i.exports,a),i.exports}e="function"==typeof Symbol?Symbol("webpack queues"):"__webpack_queues__",t="function"==typeof Symbol?Symbol("webpack exports"):"__webpack_exports__",i="function"==typeof Symbol?Symbol("webpack error"):"__webpack_error__",s=e=>{e&&e.d<1&&(e.d=1,e.forEach((e=>e.r--)),e.forEach((e=>e.r--?e.r++:e())))},a.a=(r,n,a)=>{var o;a&&((o=[]).d=-1);var h,l,c,d=new Set,u=r.exports,f=new Promise(((e,t)=>{c=t,l=e}));f[t]=u,f[e]=e=>(o&&e(o),d.forEach(e),f.catch((e=>{}))),r.exports=f,n((r=>{var n;h=(r=>r.map((r=>{if(null!==r&&"object"==typeof r){if(r[e])return r;if(r.then){var n=[];n.d=0,r.then((e=>{a[t]=e,s(n)}),(e=>{a[i]=e,s(n)}));var a={};return a[e]=e=>e(n),a}}var o={};return o[e]=e=>{},o[t]=r,o})))(r);var a=()=>h.map((e=>{if(e[i])throw e[i];return e[t]})),l=new Promise((t=>{(n=()=>t(a)).r=0;var i=e=>e!==o&&!d.has(e)&&(d.add(e),e&&!e.d&&(n.r++,e.push(n)));h.map((t=>t[e](i)))}));return n.r?l:a()}),(e=>(e?c(f[i]=e):l(u),s(o)))),o&&o.d<0&&(o.d=0)},a.d=(e,t)=>{for(var i in t)a.o(t,i)&&!a.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a(485)})(); \ No newline at end of file +(()=>{"use strict";var e,t,i,s,r={979:(e,t,i)=>{i.d(t,{u:()=>ta});var s=i(326);class r{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;r.DefaultLogoUrl?t.src=r.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(r.DefaultSpinnerUrl?s.src=r.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}r.DefaultLogoUrl="",r.DefaultSpinnerUrl="",s.$.DefaultLoadingScreenFactory=e=>new r(e);const n=1/2.2,a=(Math.sqrt(5),.001);class o{static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}const c={};function d(e,t){c[e]=t}function u(e){return c[e]}var f=i(215),_=i(315);function p(e,t,i=1401298e-51){return Math.abs(e-t)<=i}function g(e,t){return e===t?e:Math.random()*(t-e)+e}function m(e,t,i){return e+(t-e)*i}function T(e,t=0,i=1){return Math.min(i,Math.max(t,e))}function x(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function E(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}const v=e=>parseInt(e.toString().replace(/\W/g,""));class A{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=v(this.x);return e=397*e^v(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return A.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 A(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 A(this.x+e.x,this.y+e.y)}subtract(e){return new A(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 A(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 A(this.x*e,this.y*t)}divide(e){return new A(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 A(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 A(-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 A(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=a){return e&&p(this.x,e.x,t)&&p(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new A(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 A(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),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new A;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new A(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new A(0,0)}static One(){return new A(1,1)}static Random(e=0,t=1){return new A(g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(g(e,t),g(e,t))}static get ZeroReadOnly(){return A._ZeroReadOnly}static FromArray(e,t=0){return new A(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,r){const n=r*r,a=r*n,o=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*a),h=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*a);return new A(o,h)}static ClampToRef(e,t,i,s){return s.x=T(e.x,t.x,i.x),s.y=T(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=T(e.x,t.x,i.x),r=T(e.y,t.y,i.y);return new A(s,r)}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e.x*o+i.x*h+t.x*l+s.x*c,u=e.y*o+i.y*h+t.y*l+s.y*c;return new A(d,u)}static Hermite1stDerivative(e,t,i,s,r){return this.Hermite1stDerivativeToRef(e,t,i,s,r,new A)}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;return n.x=6*(a-r)*e.x+(3*a-4*r+1)*t.x+6*(-a+r)*i.x+(3*a-2*r)*s.x,n.y=6*(a-r)*e.y+(3*a-4*r+1)*t.y+6*(-a+r)*i.y+(3*a-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new A(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return A.NormalizeToRef(e,new A)}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 A(i,s)}static Transform(e,t){return A.TransformToRef(e,t,new A)}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,a=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return a>0&&o>0&&a+o<2*r*n}static Distance(e,t){return Math.sqrt(A.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 A.CenterToRef(e,t,new A)}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=A.DistanceSquared(t,i);if(0===s)return A.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,A.Dot(e.subtract(t),r)/s)),a=t.add(r.multiplyByFloats(n,n));return A.Distance(e,a)}}A._ZeroReadOnly=A.Zero(),Object.defineProperties(A.prototype,{dimension:{value:[2]},rank:{value:1}});class M{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=v(this._x);return e=397*e^v(this._y),e=397*e^v(this._z),e}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 M.FromArrayToRef(e,t,this),this}toQuaternion(){return S.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 M(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new M(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 M(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new M(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new M(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(s);return e.set(r,n,a),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,a=e._y,o=e._z,h=e._w,l=2*(a*r-o*s),c=2*(o*i-n*r),d=2*(n*s-a*i);return t._x=i+h*l+a*d-o*c,t._y=s+h*c+o*l-n*d,t._z=r+h*d+n*c-a*l,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new M)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new M)}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=I.Vector3[0];this.subtractToRef(t,n),n.normalize();const a=M.Dot(n,s);if(Math.abs(a)<1e-10)i.setAll(1/0);else{const e=-(M.Dot(t,s)+r)/a,o=n.scaleInPlace(e);t.addToRef(o,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=a){return e&&p(this._x,e._x,t)&&p(this._y,e._y,t)&&p(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new M(this._x*e,this._y*t,this._z*i)}divide(e){return new M(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!p(t,i,e))return!0;const s=Math.abs(this._z);return!p(t,s,e)||!p(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}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 M(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 M(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("xyz"===(e=e.toLowerCase()))return this;const t=I.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(I.Matrix[0]),M.TransformCoordinatesToRef(this,I.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,I.Vector3[0]),I.Vector3[0].rotateByQuaternionToRef(e,I.Vector3[0]),t.addToRef(I.Vector3[0],i),i}cross(e){return M.CrossToRef(this,e,new M)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new M)}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new M(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=M.Dot(e,i);return(r-s)/(r-M.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(I.Vector3[1]),r=t.normalizeToRef(I.Vector3[2]);let n=M.Dot(s,r);n=T(n,-1,1);const a=Math.acos(n),o=I.Vector3[3];return M.CrossToRef(s,r,o),M.Dot(o,i)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){I.Vector3[0].copyFrom(e);const s=I.Vector3[0];I.Vector3[1].copyFrom(t);const r=I.Vector3[1];I.Vector3[2].copyFrom(i);const n=I.Vector3[2],a=I.Vector3[3],o=I.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),M.CrossToRef(n,s,a),M.CrossToRef(a,n,o),x(Math.atan2(M.Dot(r,a),M.Dot(r,o)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=R.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=M.Zero();return M.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=T(i,0,1);const r=I.Vector3[0],n=I.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const h=n.length();n.normalizeFromLength(h);const l=M.Dot(r,n);let c,d;if(l<1-a){const e=Math.acos(l),t=1/Math.sin(e);c=Math.sin((1-i)*e)*t,d=Math.sin(i*e)*t}else c=1-i,d=i;return r.scaleInPlace(c),n.scaleInPlace(d),s.copyFrom(r).addInPlace(n),s.scaleInPlace(m(o,h,i)),s}static SmoothToRef(e,t,i,s,r){return M.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new M(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return M.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 M.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new M(0,0,0)}static One(){return new M(1,1,1)}static Up(){return new M(0,1,0)}static get UpReadOnly(){return M._UpReadOnly}static get DownReadOnly(){return M._DownReadOnly}static get RightReadOnly(){return M._RightReadOnly}static get LeftReadOnly(){return M._LeftReadOnly}static get LeftHandedForwardReadOnly(){return M._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return M._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return M._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return M._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return M._ZeroReadOnly}static get OneReadOnly(){return M._OneReadOnly}static Down(){return new M(0,-1,0)}static Forward(e=!1){return new M(0,0,e?-1:1)}static Backward(e=!1){return new M(0,0,e?1:-1)}static Right(){return new M(1,0,0)}static Left(){return new M(-1,0,0)}static Random(e=0,t=1){return new M(g(e,t),g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(g(e,t),g(e,t),g(e,t))}static TransformCoordinates(e,t){const i=M.Zero();return M.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return M.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],o=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],l=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=a*l,r._y=o*l,r._z=h*l,r._isDirty=!0,r}static TransformNormal(e,t){const i=M.Zero();return M.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,a=r*n,o=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*a),h=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*a),l=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*a);return new M(o,h,l)}static Clamp(e,t,i){const s=new M;return M.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:a,a=a0&&C<0?(D.copyFrom(n),O=t,F=i):C>0&&P<0?(D.copyFrom(h),O=i,F=s):(D.copyFrom(o).scaleInPlace(-1),O=s,F=t);const w=I.Vector3[9],L=I.Vector3[4];if(O.subtractToRef(x,b),F.subtractToRef(x,w),M.CrossToRef(b,w,L),!(M.Dot(L,l)<0))return r.copyFrom(x),Math.abs(p*g);const N=I.Vector3[5];M.CrossToRef(D,L,N),N.normalize();const B=I.Vector3[9];B.copyFrom(O).subtractInPlace(x);const U=B.length();if(Uthis.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 b(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 b(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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new b)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(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 M(this.x,this.y,this.z)}clone(){return new b(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 b(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 b.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new b(0,0,0,0)}static One(){return new b(1,1,1,1)}static Random(e=0,t=1){return new b(g(e,t),g(e,t),g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.x=g(e,t),i.y=g(e,t),i.z=g(e,t),i.w=g(e,t),i}static Clamp(e,t,i){return b.ClampToRef(e,t,i,new b)}static ClampToRef(e,t,i,s){return s.x=T(e.x,t.x,i.x),s.y=T(e.y,t.y,i.y),s.z=T(e.z,t.z,i.z),s.w=T(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return b._ZeroReadOnly}static Normalize(e){return b.NormalizeToRef(e,new b)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new b;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new b;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(b.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return b.CenterToRef(e,t,new b)}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 b.TransformCoordinatesToRef(e,t,new b)}static TransformCoordinatesToRef(e,t,i){return b.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],o=e*n[1]+t*n[5]+i*n[9]+n[13],h=e*n[2]+t*n[6]+i*n[10]+n[14],l=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=a,r.y=o,r.z=h,r.w=l,r}static TransformNormal(e,t){return b.TransformNormalToRef(e,t,new b)}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],a=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const a=r.m;return n.x=e*a[0]+t*a[4]+i*a[8],n.y=e*a[1]+t*a[5]+i*a[9],n.z=e*a[2]+t*a[6]+i*a[10],n.w=s,n}static FromVector3(e,t=0){return new b(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}}b._ZeroReadOnly=b.Zero(),Object.defineProperties(b.prototype,{dimension:{value:[4]},rank:{value:1}});class S{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=v(this._x);return e=397*e^v(this._y),e=397*e^v(this._z),e=397*e^v(this._w),e}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 S.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=a){return e&&p(this._x,e._x,t)&&p(this._y,e._y,t)&&p(this._z,e._z,t)&&p(this._w,e._w,t)}clone(){return new S(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 S(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 S)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new S(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 S(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 S(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}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 S)}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 S(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||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 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new S(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=M.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,a=.4999999;if(n<-a)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>a)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const a=r*r,o=t*t,h=i*i,l=s*s;e._z=Math.atan2(2*(i*s+t*r),-o-h+l+a),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),o-h-l+a),e._isDirty=!0}return e}toRotationMatrix(e){return y.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return S.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 S;return S.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[1],o=i[5],h=i[9],l=i[2],c=i[6],d=i[10],u=s+o+d;let f;return u>0?(f=.5/Math.sqrt(u+1),t._w=.25/f,t._x=(c-h)*f,t._y=(n-l)*f,t._z=(a-r)*f,t._isDirty=!0):s>o&&s>d?(f=2*Math.sqrt(1+s-o-d),t._w=(c-h)/f,t._x=.25*f,t._y=(r+a)/f,t._z=(n+l)/f,t._isDirty=!0):o>d?(f=2*Math.sqrt(1+o-s-d),t._w=(n-l)/f,t._x=(r+a)/f,t._y=.25*f,t._z=(h+c)/f,t._isDirty=!0):(f=2*Math.sqrt(1+d-s-o),t._w=(a-r)/f,t._x=(n+l)/f,t._y=(h+c)/f,t._z=.25*f,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=S.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=T(n,0,1),S.SlerpToRef(e,t,n,r),r}static Zero(){return new S(0,0,0,0)}static Inverse(e){return new S(-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 S(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return S.RotationAxisToRef(e,t,new S)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new S(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,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new S;return S.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return S.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new S;return S.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return S.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=a){const r=M.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(M.CrossToRef(e,t,R.Vector3[0]),i.set(R.Vector3[0].x,R.Vector3[0].y,R.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new S;return S.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,a=.5*e,o=Math.sin(r),h=Math.cos(r),l=Math.sin(n),c=Math.cos(n),d=Math.sin(a),u=Math.cos(a);return s._x=u*l*h+d*c*o,s._y=d*c*h-u*l*o,s._z=u*c*o-d*l*h,s._w=u*c*h+d*l*o,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new S;return S.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),a=.5*t;return s._x=Math.cos(n)*Math.sin(a),s._y=Math.sin(n)*Math.sin(a),s._z=Math.sin(r)*Math.cos(a),s._w=Math.cos(r)*Math.cos(a),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new S(0,0,0,0);return S.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=I.Matrix[0];return y.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),S.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new S;return S.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=I.Matrix[0];return y.LookDirectionLHToRef(e,t,s),S.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new S;return S.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=I.Matrix[0];return y.LookDirectionRHToRef(e,t,s),S.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=S.Identity();return S.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,o=!1;if(a<0&&(o=!0,a=-a),a>.999999)n=1-i,r=o?-i:i;else{const e=Math.acos(a),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e._x*o+i._x*h+t._x*l+s._x*c,u=e._y*o+i._y*h+t._y*l+s._y*c,f=e._z*o+i._z*h+t._z*l+s._z*c,_=e._w*o+i._w*h+t._w*l+s._w*c;return new S(d,u,f,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new S;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;return n._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*i._x+(3*a-2*r)*s._x,n._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*i._y+(3*a-2*r)*s._y,n._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*i._z+(3*a-2*r)*s._z,n._w=6*(a-r)*e._w+(3*a-4*r+1)*t._w+6*(-a+r)*i._w+(3*a-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=S.Zero();return S.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new S;return S.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(T(e.x,t.x,i.x),T(e.y,t.y,i.y),T(e.z,t.z,i.z),T(e.w,t.w,i.w))}static Random(e=0,t=1){return new S(g(e,t),g(e,t),g(e,t),g(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(g(e,t),g(e,t),g(e,t),g(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(S.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return S.CenterToRef(e,t,S.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(S.prototype,{dimension:{value:[4]},rank:{value:1}});class y{static get Use64Bits(){return f.I.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=y._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&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,f.I.MatrixTrackPrecisionChange&&f.I.MatrixTrackedMatrices.push(this),this._m=new f.I.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==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]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8],c=e[9],d=e[10],u=e[11],f=e[12],_=e[13],p=e[14],g=e[15],m=d*g-p*u,T=c*g-_*u,x=c*p-_*d,E=l*g-f*u,v=l*p-d*f,A=l*_-f*c;return t*+(a*m-o*T+h*x)+i*-(n*m-o*E+h*v)+s*+(n*T-a*E+h*A)+r*-(n*x-a*v+o*A)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return y.FromArrayToRef(e,t,this)}copyFromFloats(...e){return y.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 y.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 y;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];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 e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new y)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return y.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],a=t[4],o=t[5],h=t[6],l=t[7],c=t[8],d=t[9],u=t[10],f=t[11],_=t[12],p=t[13],g=t[14],m=t[15],T=u*m-g*f,x=d*m-p*f,E=d*g-p*u,v=c*m-_*f,A=c*g-u*_,M=c*p-_*d,b=+(o*T-h*x+l*E),S=-(a*T-h*v+l*A),I=+(a*x-o*v+l*M),R=-(a*E-o*A+h*M),C=i*b+s*S+r*I+n*R;if(0===C)return e.copyFrom(this),e;const P=1/C,D=h*m-g*l,O=o*m-p*l,F=o*g-p*h,w=a*m-_*l,L=a*g-_*h,N=a*p-_*o,B=h*f-u*l,U=o*f-d*l,k=o*u-d*h,V=a*f-c*l,G=a*u-c*h,z=a*d-c*o,W=-(s*T-r*x+n*E),X=+(i*T-r*v+n*A),H=-(i*x-s*v+n*M),K=+(i*E-s*A+r*M),Y=+(s*D-r*O+n*F),q=-(i*D-r*w+n*L),j=+(i*O-s*w+n*N),Z=-(i*F-s*L+r*N),Q=-(s*B-r*U+n*k),$=+(i*B-r*V+n*G),J=-(i*U-s*V+n*z),ee=+(i*k-s*G+r*z);return y.FromValuesToRef(b*P,W*P,Y*P,Q*P,S*P,X*P,q*P,$*P,I*P,H*P,j*P,J*P,R*P,K*P,Z*P,ee*P,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 M(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 y.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),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 y;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];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,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];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,r=e.m,n=s[0],a=s[1],o=s[2],h=s[3],l=s[4],c=s[5],d=s[6],u=s[7],f=s[8],_=s[9],p=s[10],g=s[11],m=s[12],T=s[13],x=s[14],E=s[15],v=r[0],A=r[1],M=r[2],b=r[3],S=r[4],y=r[5],I=r[6],R=r[7],C=r[8],P=r[9],D=r[10],O=r[11],F=r[12],w=r[13],L=r[14],N=r[15];return t[i]=n*v+a*S+o*C+h*F,t[i+1]=n*A+a*y+o*P+h*w,t[i+2]=n*M+a*I+o*D+h*L,t[i+3]=n*b+a*R+o*O+h*N,t[i+4]=l*v+c*S+d*C+u*F,t[i+5]=l*A+c*y+d*P+u*w,t[i+6]=l*M+c*I+d*D+u*L,t[i+7]=l*b+c*R+d*O+u*N,t[i+8]=f*v+_*S+p*C+g*F,t[i+9]=f*A+_*y+p*P+g*w,t[i+10]=f*M+_*I+p*D+g*L,t[i+11]=f*b+_*R+p*O+g*N,t[i+12]=m*v+T*S+x*C+E*F,t[i+13]=m*A+T*y+x*P+E*w,t[i+14]=m*M+T*I+x*D+E*L,t[i+15]=m*b+T*R+x*O+E*N,this}divide(e){return this.divideToRef(e,new y)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);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 y)}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 e=0;e<16;e++)i[e]=-t[e];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 e=0;e<16;e++)if(!p(i[e],s[e],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 y)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new y)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new y;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=v(this._m[0]);for(let t=1;t<16;t++)e=397*e^v(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new S,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||I.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;y.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,I.Matrix[0]),S.FromRotationMatrixToRef(I.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new b(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=4*e;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 y;return y.TransposeToRef(this,e),e}transposeToRef(e){return y.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new y;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=I.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return y.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 y;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=I.Vector3[0];if(!this.decompose(t))return y.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return y.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new y;return y.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return y._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,a,o,h,l,c,d,u,f,_,p,g){const m=g._m;m[0]=e,m[1]=t,m[2]=i,m[3]=s,m[4]=r,m[5]=n,m[6]=a,m[7]=o,m[8]=h,m[9]=l,m[10]=c,m[11]=d,m[12]=u,m[13]=f,m[14]=_,m[15]=p,g.markAsUpdated()}static FromValues(e,t,i,s,r,n,a,o,h,l,c,d,u,f,_,p){const g=new y,m=g._m;return m[0]=e,m[1]=t,m[2]=i,m[3]=s,m[4]=r,m[5]=n,m[6]=a,m[7]=o,m[8]=h,m[9]=l,m[10]=c,m[11]=d,m[12]=u,m[13]=f,m[14]=_,m[15]=p,g.markAsUpdated(),g}static Compose(e,t,i){const s=new y;return y.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,a=t._y,o=t._z,h=t._w,l=n+n,c=a+a,d=o+o,u=n*l,f=n*c,_=n*d,p=a*c,g=a*d,m=o*d,T=h*l,x=h*c,E=h*d,v=e._x,A=e._y,M=e._z;return r[0]=(1-(p+m))*v,r[1]=(f+E)*v,r[2]=(_-x)*v,r[3]=0,r[4]=(f-E)*A,r[5]=(1-(u+m))*A,r[6]=(g+T)*A,r[7]=0,r[8]=(_+x)*M,r[9]=(g-T)*M,r[10]=(1-(u+p))*M,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=y.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 y.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=y.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 y;return y.RotationXToRef(e,t),t}static Invert(e){const t=new y;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return y.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new y;return y.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return y.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new y;return y.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return y.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new y;return y.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const a=i._m;return a[0]=e._x*e._x*n+r,a[1]=e._x*e._y*n-e._z*s,a[2]=e._x*e._z*n+e._y*s,a[3]=0,a[4]=e._y*e._x*n+e._z*s,a[5]=e._y*e._y*n+r,a[6]=e._y*e._z*n-e._x*s,a[7]=0,a[8]=e._z*e._x*n-e._y*s,a[9]=e._z*e._y*n+e._x*s,a[10]=e._z*e._z*n+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=M.Dot(t,e),n=i._m;if(r<-1+a)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=M.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new y;return y.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return S.RotationYawPitchRollToRef(e,t,i,I.Quaternion[0]),I.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new y;return y.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return y.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new y;return y.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return y.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new y;return y.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,a=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+a[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new y;return y.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=I.Vector3[0],n=I.Quaternion[0],a=I.Vector3[1];e.decompose(r,n,a);const o=I.Vector3[2],h=I.Quaternion[1],l=I.Vector3[3];t.decompose(o,h,l);const c=I.Vector3[4];M.LerpToRef(r,o,i,c);const d=I.Quaternion[2];S.SlerpToRef(n,h,i,d);const u=I.Vector3[5];return M.LerpToRef(a,l,i,u),y.ComposeToRef(c,d,u,s),s}static LookAtLH(e,t,i){const s=new y;return y.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=I.Vector3[0],n=I.Vector3[1],a=I.Vector3[2];t.subtractToRef(e,a),a.normalize(),M.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),M.CrossToRef(a,r,n),n.normalize();const h=-M.Dot(r,e),l=-M.Dot(n,e),c=-M.Dot(a,e);return y.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,s),s}static LookAtRH(e,t,i){const s=new y;return y.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=I.Vector3[0],n=I.Vector3[1],a=I.Vector3[2];e.subtractToRef(t,a),a.normalize(),M.CrossToRef(i,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),M.CrossToRef(a,r,n),n.normalize();const h=-M.Dot(r,e),l=-M.Dot(n,e),c=-M.Dot(a,e);return y.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,s),s}static LookDirectionLH(e,t){const i=new y;return y.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=I.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=I.Vector3[1];return M.CrossToRef(t,s,r),y.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new y;return y.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=I.Vector3[2];return M.CrossToRef(t,e,s),y.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new y;return y.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const a=2/e,o=2/t,h=2/(s-i),l=-(s+i)/(s-i);return y.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,h,0,0,0,l,1,r),n&&r.multiplyToRef(C,r),r._updateIdentityStatus(1===a&&1===o&&1===h&&0===l),r}static OrthoOffCenterLH(e,t,i,s,r,n,a){const o=new y;return y.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o}static OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o){const h=2/(t-e),l=2/(s-i),c=2/(n-r),d=-(n+r)/(n-r),u=(e+t)/(e-t),f=(s+i)/(i-s);return y.FromValuesToRef(h,0,0,0,0,l,0,0,0,0,c,0,u,f,d,1,a),o&&a.multiplyToRef(C,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,a,o,h,l,c){const d=-a*Math.cos(o),u=-a*Math.sin(o);return y.TranslationToRef(0,0,-h,I.Matrix[1]),y.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,I.Matrix[0]),I.Matrix[1].multiplyToRef(I.Matrix[0],I.Matrix[0]),y.TranslationToRef(0,0,h,I.Matrix[1]),I.Matrix[0].multiplyToRef(I.Matrix[1],I.Matrix[0]),y.OrthoOffCenterLHToRef(e,t,i,s,r,n,l,c),I.Matrix[0].multiplyToRef(l,l),l}static OrthoOffCenterRH(e,t,i,s,r,n,a){const o=new y;return y.OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a),o}static OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o){return y.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,a,o,h,l,c){const d=a*Math.cos(o),u=a*Math.sin(o);return y.TranslationToRef(0,0,h,I.Matrix[1]),y.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,I.Matrix[0]),I.Matrix[1].multiplyToRef(I.Matrix[0],I.Matrix[0]),y.TranslationToRef(0,0,-h,I.Matrix[1]),I.Matrix[0].multiplyToRef(I.Matrix[1],I.Matrix[0]),y.OrthoOffCenterRHToRef(e,t,i,s,r,n,l,c),I.Matrix[0].multiplyToRef(l,l),l}static PerspectiveLH(e,t,i,s,r,n=0){const a=new y,o=2*i/e,h=2*i/t,l=(s+i)/(s-i),c=-2*s*i/(s-i),d=Math.tan(n);return y.FromValuesToRef(o,0,0,0,0,h,0,d,0,0,l,1,0,0,c,0,a),r&&a.multiplyToRef(C,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,s,r,n=0,a=!1){const o=new y;return y.PerspectiveFovLHToRef(e,t,i,s,o,!0,r,n,a),o}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,a,o=0,h=!1){const l=i,c=s,d=1/Math.tan(.5*e),u=n?d/t:d,f=n?d:d*t,_=h&&0===l?-1:0!==c?(c+l)/(c-l):1,p=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,g=Math.tan(o);return y.FromValuesToRef(u,0,0,0,0,f,0,g,0,0,_,1,0,0,p,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,d=Math.tan(o);return y.FromValuesToRef(l,0,0,0,0,c,0,d,0,0,-i,1,0,0,1,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,a=!1){const o=new y;return y.PerspectiveFovRHToRef(e,t,i,s,o,!0,r,n,a),o}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,a,o=0,h=!1){const l=i,c=s,d=1/Math.tan(.5*e),u=n?d/t:d,f=n?d:d*t,_=h&&0===l?1:0!==c?-(c+l)/(c-l):-1,p=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,g=Math.tan(o);return y.FromValuesToRef(u,0,0,0,0,f,0,g,0,0,_,-1,0,0,p,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,d=Math.tan(o);return y.FromValuesToRef(l,0,0,0,0,c,0,d,0,0,-i,-1,0,0,-1,0,r),a&&r.multiplyToRef(C,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const a=e.width,o=e.height,h=e.x,l=e.y,c=y.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,n-r,0,h+a/2,o/2+l,r,1),d=new y;return t.multiplyToRef(i,d),d.multiplyToRef(s,d),d.multiplyToRef(c,d)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return f.I.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 f.I.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new y;return y.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],a=i[12],o=i[1],h=i[5],l=i[9],c=i[13],d=i[2],u=i[6],f=i[10],_=i[14],p=i[3],g=i[7],m=i[11],T=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=a,x[4]=o,x[5]=h,x[6]=l,x[7]=c,x[8]=d,x[9]=u,x[10]=f,x[11]=_,x[12]=p,x[13]=g,x[14]=m,x[15]=T,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new y;return y.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,a=-2*s,o=-2*r;return y.FromValuesToRef(n*i+1,a*i,o*i,0,n*s,a*s+1,o*s,0,n*r,a*r,o*r+1,0,n*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return y.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,a=e._z*e._w,o=e._z*e._x,h=e._y*e._w,l=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+a),t._m[2]=2*(o-h),t._m[3]=0,t._m[4]=2*(n-a),t._m[5]=1-2*(r+i),t._m[6]=2*(l+c),t._m[7]=0,t._m[8]=2*(o+h),t._m[9]=2*(l-c),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}}y._UpdateFlagSeed=0,y._IdentityReadOnly=y.Identity(),Object.defineProperties(y.prototype,{dimension:{value:[4,4]},rank:{value:2}});class I{}I.Vector3=o.BuildTuple(11,M.Zero),I.Matrix=o.BuildTuple(2,y.Identity),I.Quaternion=o.BuildTuple(3,S.Zero);class R{}R.Vector2=o.BuildTuple(3,A.Zero),R.Vector3=o.BuildTuple(13,M.Zero),R.Vector4=o.BuildTuple(3,b.Zero),R.Quaternion=o.BuildTuple(2,S.Zero),R.Matrix=o.BuildTuple(8,y.Identity),d("BABYLON.Vector2",A),d("BABYLON.Vector3",M),d("BABYLON.Vector4",b),d("BABYLON.Matrix",y);const C=y.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class P{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=P.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=P.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=P.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+P.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=P.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*T(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?T((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,a=r*n;return e*(2*a-3*n+1)+i*(-2*a+3*n)+t*(a-2*n+r)+s*(a-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:P.HCF(t,i)}}function D(e){return Math.pow(e,2.2)}function O(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function F(e){return Math.pow(e,n)}function w(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}P.TwoPi=2*Math.PI,P.WithinEpsilon=p,P.ToHex=E,P.Clamp=T,P.Lerp=m,P.RandomRange=g,P.NormalizeRadians=x;class L{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=255*this.r|0;return e=397*e^(255*this.g|0),e=397*e^(255*this.b|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 L.FromArrayToRef(e,t,this),this}toColor4(e=1){return new N(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new L(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 L(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=a){return P.WithinEpsilon(this.r,e.r,t)&&P.WithinEpsilon(this.g,e.g,t)&&P.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new L(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=T(this.r,e,t),i.g=T(this.g,e,t),i.b=T(this.b,e,t),i}add(e){return new L(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 L(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 L(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 L(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(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+E(e)+E(t)+E(i)}toHSV(){return this.toHSVToRef(new L)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let a=0,o=0;const h=r,l=r-n;return 0!==r&&(o=l/r),r!=n&&(r==t?(a=(i-s)/l,i=0&&n<=1?(o=r,h=a):n>=1&&n<=2?(o=a,h=r):n>=2&&n<=3?(h=r,l=a):n>=3&&n<=4?(h=a,l=r):n>=4&&n<=5?(o=a,l=r):n>=5&&n<=6&&(o=r,l=a);const c=i-r;return s.r=o+c,s.g=h+c,s.b=l+c,s}static FromHSV(e,t,i){const s=new L(0,0,0);return L.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new L(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return L.FromInts(t,i,s)}static FromArray(e,t=0){return new L(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 L(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new L(0,0,0);return L.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e.r*o+i.r*h+t.r*l+s.r*c,u=e.g*o+i.g*h+t.g*l+s.g*c,f=e.b*o+i.b*h+t.b*l+s.b*c;return new L(d,u,f)}static Hermite1stDerivative(e,t,i,s,r){const n=L.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*s.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*s.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*s.b}static Red(){return new L(1,0,0)}static Green(){return new L(0,1,0)}static Blue(){return new L(0,0,1)}static Black(){return new L(0,0,0)}static get BlackReadOnly(){return L._BlackReadOnly}static White(){return new L(1,1,1)}static Purple(){return new L(.5,0,.5)}static Magenta(){return new L(1,0,1)}static Yellow(){return new L(1,1,0)}static Gray(){return new L(.5,.5,.5)}static Teal(){return new L(0,1,1)}static Random(){return new L(Math.random(),Math.random(),Math.random())}}L._BlackReadOnly=L.Black(),Object.defineProperties(L.prototype,{dimension:{value:[3]},rank:{value:1}});class N{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 N(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 N(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 N(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new N(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=T(this.r,e,t),i.g=T(this.g,e,t),i.b=T(this.b,e,t),i.a=T(this.a,e,t),i}multiply(e){return new N(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 N(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=a){return P.WithinEpsilon(this.r,e.r,t)&&P.WithinEpsilon(this.g,e.g,t)&&P.WithinEpsilon(this.b,e.b,t)&&P.WithinEpsilon(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=255*this.r|0;return e=397*e^(255*this.g|0),e=397*e^(255*this.b|0),e=397*e^(255*this.a|0),e}clone(){return(new N).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(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+E(t)+E(i)+E(s);const r=Math.round(255*this.a);return"#"+E(t)+E(i)+E(s)+E(r)}toLinearSpace(e=!1){const t=new N;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=O(this.r),e.g=O(this.g),e.b=O(this.b)):(e.r=D(this.r),e.g=D(this.g),e.b=D(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new N;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=w(this.r),e.g=w(this.g),e.b=w(this.b)):(e.r=F(this.r),e.g=F(this.g),e.b=F(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new N(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return N.FromInts(t,i,s,r)}static Lerp(e,t,i){return N.LerpToRef(e,t,i,new N)}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,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,d=e.r*o+i.r*h+t.r*l+s.r*c,u=e.g*o+i.g*h+t.g*l+s.g*c,f=e.b*o+i.b*h+t.b*l+s.b*c,_=e.a*o+i.a*h+t.a*l+s.a*c;return new N(d,u,f,_)}static Hermite1stDerivative(e,t,i,s,r){const n=new N;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*i.r+(3*a-2*r)*s.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*i.g+(3*a-2*r)*s.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*i.b+(3*a-2*r)*s.b,n.a=6*(a-r)*e.a+(3*a-4*r+1)*t.a+6*(-a+r)*i.a+(3*a-2*r)*s.a}static FromColor3(e,t=1){return new N(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new N(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 N(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew N(0,0,0,0))),d("BABYLON.Color3",L),d("BABYLON.Color4",N);var U=i(504),k=i(137);class V{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,r=!1,n=!1,a=!1,o,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=n,this._divisor=o||1,this._label=h,t instanceof U.n?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,s,r,n=!1,a){const o=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=s?n?s:s*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new G(this._engine,this,e,this._updatable,!0,h,void 0===r?this._instanced:r,o,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));k.V.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,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),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class G{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;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,r,n,a,o,h,l,c=!1,d=!1,u=1,f=!1){this._isDisposed=!1;let _=!1;if(this.engine=e,"object"==typeof s&&null!==s?(_=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,a=s.instanced,o=s.offset,h=s.size,l=s.type,c=s.normalized??!1,d=s.useBytes??!1,u=s.divisor??1,f=s.takeBufferOwnership??!1,this._label=s.label):_=!!s,t instanceof V?(this._buffer=t,this._ownsBuffer=f):(this._buffer=new V(e,t,_,n,r,a,d,u,this._label),this._ownsBuffer=!0),this.uniqueId=G._Counter++,this._kind=i,void 0===l){const e=this.getData();this.type=e?G.GetDataType(e):G.FLOAT}else this.type=l;const p=G.GetTypeByteLength(this.type);d?(this._size=h||(n?n/p:G.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*p,this.byteOffset=o||0):(this._size=h||n||G.DeduceStride(i),this.byteStride=n?n*p:this._buffer.byteStride||this._size*p,this.byteOffset=(o||0)*p),this.normalized=c,this._instanced=void 0!==a&&a,this._instanceDivisor=a?u: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(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?G.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/G.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/G.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*G.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){G.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case G.UVKind:case G.UV2Kind:case G.UV3Kind:case G.UV4Kind:case G.UV5Kind:case G.UV6Kind:return 2;case G.NormalKind:case G.PositionKind:return 3;case G.ColorKind:case G.ColorInstanceKind:case G.MatricesIndicesKind:case G.MatricesIndicesExtraKind:case G.MatricesWeightsKind:case G.MatricesWeightsExtraKind:case G.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?G.BYTE:e instanceof Uint8Array?G.UNSIGNED_BYTE:e instanceof Int16Array?G.SHORT:e instanceof Uint16Array?G.UNSIGNED_SHORT:e instanceof Int32Array?G.INT:e instanceof Uint32Array?G.UNSIGNED_INT:G.FLOAT}static GetTypeByteLength(e){switch(e){case G.BYTE:case G.UNSIGNED_BYTE:return 1;case G.SHORT:case G.UNSIGNED_SHORT:return 2;case G.INT:case G.UNSIGNED_INT:case G.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,a,o){if(e instanceof Array){let r=t/4;const a=i/4;for(let t=0;ta[t]=e)),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==l){if(e instanceof Array){const t=s/4;return e.slice(t,t+l)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,l);{let t=e.byteOffset+s;if(o){const i=new Float32Array(l),s=new Float32Array(e.buffer,t,l);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,l)}}return o?e.slice():e}}function z(e,t,i,s){var r,n=arguments.length,a=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,s);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(n<3?r(a):n>3?r(t,i,a):r(t,i))||a);return n>3&&a&&Object.defineProperty(t,i,a),a}G._Counter=0,G.BYTE=5120,G.UNSIGNED_BYTE=5121,G.SHORT=5122,G.UNSIGNED_SHORT=5123,G.INT=5124,G.UNSIGNED_INT=5125,G.FLOAT=5126,G.PositionKind="position",G.NormalKind="normal",G.TangentKind="tangent",G.UVKind="uv",G.UV2Kind="uv2",G.UV3Kind="uv3",G.UV4Kind="uv4",G.UV5Kind="uv5",G.UV6Kind="uv6",G.ColorKind="color",G.ColorInstanceKind="instanceColor",G.MatricesIndicesKind="matricesIndices",G.MatricesWeightsKind="matricesWeights",G.MatricesIndicesExtraKind="matricesIndicesExtra",G.MatricesWeightsExtraKind="matricesWeightsExtra",Object.create,Object.create;const W={},X={};function H(e){const t=e.getClassName();if(W[t])return W[t];W[t]={};const i=W[t];let s=e,r=t;for(;r;){const e=X[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function K(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return X[t]||(X[t]={}),X[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function Y(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function q(e){return K(0,e)}function j(e){return K(1,e)}function Z(e){return K(2,e)}function Q(e){return K(3,e)}function $(e){return K(4,e)}function J(e){return K(5,e)}function ee(e){return K(6,e)}function te(e){return K(8,e)}function ie(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}ie.filter=function(e){return(t,i,s)=>ie(t,i,s,e)};var se=i(848),re=i(503);class ne{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),ne._HandleParenthesisContent(e,t)))):ne._HandleParenthesisContent(e,t))||"false"!==e&&ne.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=ne._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class ae{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>ae.HasTags(e),e.addTags=t=>ae.AddTagsTo(e,t),e.removeTags=t=>ae.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>ae.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 e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){ae._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(ae.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!ae.HasTags(e))return;const i=t.split(" ");for(const t in i)ae._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?ae.HasTags(e):ne.Eval(t,(t=>ae.HasTags(e)&&e._tags[t])))}}const oe=function(e,t,i,s={}){const r=e();ae&&ae.HasTags(t)&&ae.AddTagsTo(r,ae.GetTags(t,!0));const n=H(r),a={};for(const e in n){const o=n[e],h=t[e],l=o.type;if(null!=h&&("uniqueId"!==e||he.AllowLoadingUniqueId))switch(l){case 0:case 6:case 11:r[e]=h;break;case 1:s.cloneTexturesOnlyOnce&&a[h.uniqueId]?r[e]=a[h.uniqueId]:(r[e]=i||h.isRenderTarget?h:h.clone(),a[h.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?h:h.clone()}}return r};class he{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw(0,re.n)("ImageProcessingConfiguration")},he._FresnelParametersParser=e=>{throw(0,re.n)("FresnelParameters")},he._ColorCurvesParser=e=>{throw(0,re.n)("ColorCurves")},he._TextureParser=(e,t,i)=>{throw(0,re.n)("Texture")};class le{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new se.cP,this._onClonedObservable=new se.cP}}class ce{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(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||!!this._parentNode&&this._parentNode.doNotSerialize}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&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(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(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){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 le,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new se.cP,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=y.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new se.cP,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||_.q.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-1!==this._behaviors.indexOf(e)||(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-1===t||(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&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&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!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),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||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew ce(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw(0,re.n)("AnimationRange")},ce._NodeConstructors={},z([q()],ce.prototype,"name",void 0),z([q()],ce.prototype,"id",void 0),z([q()],ce.prototype,"uniqueId",void 0),z([q()],ce.prototype,"state",void 0),z([q()],ce.prototype,"metadata",void 0);var de=i(790);const ue=(e,t,i)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class fe{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const a of n){if("_"===a[0]&&(!s||-1===s.indexOf(a)))continue;if(a.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(a))continue;const n=e[a],o=typeof n;if("function"!==o)try{if("object"===o)if(n instanceof Uint8Array)t[a]=Uint8Array.from(n);else if(n instanceof Array){if(t[a]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e0||pe.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in pe.CustomRequestHeaders){const t=pe.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return pe.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){pe.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of pe.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).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)}}pe.CustomRequestHeaders={},pe.CustomRequestModifiers=new Array,pe.SkipRequestModificationForBabylonCDN=!0;class ge{}ge.FilesToLoad={};class me extends Error{}me._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Te=3e3;class xe extends me{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",me._setPrototypeOf(this,xe.prototype)}}const Ee=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,a,o,h,l="",c=0;const d=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,a=(3&i)<<4|s>>4,o=(15&s)<<2|r>>6,h=63&r,isNaN(s)?o=h=64:isNaN(r)&&(h=64),l+=t.charAt(n)+t.charAt(a)+t.charAt(o)+t.charAt(h);return l},ve=e=>atob(e);var Ae=i(125);class Me{static SetImmediate(e){(0,de.BA)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}var be=i(741);const Se=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class ye extends xe{constructor(e,t){super(e,4e3),this.name="LoadFileError",me._setPrototypeOf(this,ye.prototype),t instanceof pe?this.request=t:this.file=t}}class Ie extends xe{constructor(e,t){super(e,4001),this.request=t,this.name="RequestFileError",me._setPrototypeOf(this,Ie.prototype)}}class Re extends xe{constructor(e,t){super(e,4002),this.file=t,this.name="ReadFileError",me._setPrototypeOf(this,Re.prototype)}}const Ce={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},Pe=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&Ce.CorsBehavior)if("string"==typeof Ce.CorsBehavior||Ce.CorsBehavior instanceof String)t.crossOrigin=Ce.CorsBehavior;else{const i=Ce.CorsBehavior(e);i&&(t.crossOrigin=i)}},De=(e,t,i,s,r="",n)=>{const a=_.q.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!a?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let o,h=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:r})),h=!0):o=`data:${r};base64,`+Ee(e):e instanceof Blob?(o=URL.createObjectURL(e),h=!0):(o=Ce.CleanUrl(e),o=Ce.PreprocessUrl(e));const l=t=>{if(i){const s=o||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(a?._features.forceBitmapOverHTMLImageElement)return Fe(o,(s=>{a.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),h&&URL.revokeObjectURL(o)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{l(t)})),null;const c=new Image;Pe(o,c);const d=[],u=()=>{d.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),d.length=0};d.push({target:c,name:"load",handler:()=>{u(),t(c),h&&c.src&&URL.revokeObjectURL(c.src)}}),d.push({target:c,name:"error",handler:e=>{u(),l(e),h&&c.src&&URL.revokeObjectURL(c.src)}}),d.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;u();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);_.q.UseFallbackTexture=!1,l(t),h&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),d.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const f="blob:"===o.substring(0,5),p="data:"===o.substring(0,5),g=()=>{f||p||!pe.IsCustomRequestAvailable?c.src=o:Fe(o,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);h=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{l(t)}))};if(!f&&!p&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(o,c)}),g);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(ge.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(ge.FilesToLoad[e])}catch(i){t=URL.createObjectURL(ge.FilesToLoad[e])}c.src=t,h=!0}catch(e){c.src=""}return c}}g()}return c},Oe=(e,t,i,s,r)=>{const n=new FileReader,a={onCompleteObservable:new se.cP,abort:()=>n.abort()};return n.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(n.onerror=()=>{r(new Re(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),a},Fe=(e,t,i,s,r,n,a)=>{if(e.name)return Oe(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const o=e;if(-1!==o.indexOf("file:")){let e=decodeURIComponent(o.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=ge.FilesToLoad[e];if(s)return Oe(s,t,i,r,n?e=>n(void 0,new ye(e.message,e.file)):void 0)}const{match:h,type:l}=Be(o);if(h){const e={onCompleteObservable:new se.cP,abort:()=>()=>{}};try{const e=r?Ue(o):ke(o);t(e,void 0,l)}catch(e){n?n(void 0,e):k.V.Error(e.message||"Failed to parse the Data URL")}return Me.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return we(o,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new ye(e.message,e.request))}:void 0,a)},we=(e,t,i,s,r,n,a)=>{e=Ce.CleanUrl(e),e=Ce.PreprocessUrl(e);const o=Ce.BaseUrl+e;let h=!1;const l={onCompleteObservable:new se.cP,abort:()=>h=!0},c=()=>{let e,s=new pe,c=null;const d=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",u))};let u=()=>{d(),l.onCompleteObservable.notifyObservers(l),l.onCompleteObservable.clear(),i=void 0,e=null,u=null,n=void 0,a=void 0,t=void 0};l.abort=()=>{h=!0,u&&u(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const f=e=>{const t=e.message||"Unknown error";n&&s?n(new Ie(t,s)):k.V.Error(t)},_=l=>{if(s){if(s.open("GET",o),a)try{a(s)}catch(e){return void f(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),u&&s.addEventListener("loadend",u),e=()=>{if(!h&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!(0,de.BA)()||Le())){try{t&&t(r?s.response:s.responseText,s)}catch(e){f(e)}return}const i=Ce.DefaultRetryStrategy;if(i){const e=i(o,s,l);if(-1!==e)return d(),s=new pe,void(c=setTimeout((()=>_(l+1)),e))}const a=new Ie("Error status: "+s.status+" "+s.statusText+" - Unable to load "+o,s);n&&n(a)}},s.addEventListener("readystatechange",e),s.send()}};_(0)};if(s&&s.enableSceneOffline){const a=e=>{e&&e.status>400?n&&n(e):c()},o=()=>{s&&s.loadFile(Ce.BaseUrl+e,(e=>{!h&&t&&t(e),l.onCompleteObservable.notifyObservers(l)}),i?e=>{!h&&i&&i(e)}:void 0,a,r)};s.open(o,a)}else c();return l},Le=()=>"undefined"!=typeof location&&"file:"===location.protocol,Ne=e=>Se.test(e),Be=e=>{const t=Se.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Ue(e){return(e=>{const t=ve(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;eve(e.split(",")[1]);let Ve;s.$._FileToolsLoadImage=De,be.sg.loadFile=Fe,Ae.J.loadFile=Fe,((e,t,i,s,r,n,a,o,h,l)=>{Ve={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:a,ReadFile:o,RequestFile:h,SetCorsBehavior:l},Object.defineProperty(Ve,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Ve,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Ve,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Ve,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(Ue,ke,Ce,Ne,Le,Fe,De,Oe,we,Pe);class Ge{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=u(e);if(t)return t;k.V.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}Ge.RegisteredExternalClasses={};var We=i(597);class Xe{static get BaseUrl(){return Ce.BaseUrl}static set BaseUrl(e){Ce.BaseUrl=e}static get CleanUrl(){return Ce.CleanUrl}static set CleanUrl(e){Ce.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){Fe(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Xe.ScriptBaseUrl&&e.startsWith(Xe._DefaultCdnUrl)){const t="/"===Xe.ScriptBaseUrl[Xe.ScriptBaseUrl.length-1]?Xe.ScriptBaseUrl.substring(0,Xe.ScriptBaseUrl.length-1):Xe.ScriptBaseUrl;e=e.replace(Xe._DefaultCdnUrl,t)}return e=Xe.ScriptPreprocessUrl(e),t&&(e=Xe.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Xe.GetBabylonScriptURL(e),Xe.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Xe.GetBabylonScriptURL(e),Xe.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!(0,de.BA)())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new se.cP,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return Oe(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){fe.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 s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}Xe.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(Xe._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&Xe.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)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"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,a){throw(0,re.n)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw(0,re.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,a=!1,o,h=!1,l=!1,c=!0,d){throw(0,re.n)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,a,o=!1,h=!1,l=!0,c){throw(0,re.n)("ScreenshotTools")}static RandomId(){return ze()}static IsBase64(e){return Ne(e)}static DecodeBase64(e){return Ue(e)}static get errorsCount(){return k.V.errorsCount}static Log(e){k.V.Log(e)}static Warn(e){k.V.Warn(e)}static Error(e){k.V.Error(e)}static get LogCache(){return k.V.LogCache}static ClearLogCache(){k.V.ClearLogCache()}static set LogLevels(e){k.V.LogLevels=e}static set PerformanceLogLevel(e){return(e&Xe.PerformanceUserMarkLogLevel)===Xe.PerformanceUserMarkLogLevel?(Xe.StartPerformanceCounter=Xe._StartUserMark,void(Xe.EndPerformanceCounter=Xe._EndUserMark)):(e&Xe.PerformanceConsoleLogLevel)===Xe.PerformanceConsoleLogLevel?(Xe.StartPerformanceCounter=Xe._StartPerformanceConsole,void(Xe.EndPerformanceCounter=Xe._EndPerformanceConsole)):(Xe.StartPerformanceCounter=Xe._StartPerformanceCounterDisabled,void(Xe.EndPerformanceCounter=Xe._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Xe._Performance){if(!(0,de.BA)())return;Xe._Performance=window.performance}t&&Xe._Performance.mark&&Xe._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Xe._Performance.mark&&(Xe._Performance.mark(e+"-End"),Xe._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Xe._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Xe._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return _e.j.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!(0,de.XD)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Xe.UseCustomRequestHeaders=!1,Xe.CustomRequestHeaders=pe.CustomRequestHeaders,Xe.GetDOMTextContent=de.Zl,Xe._DefaultCdnUrl="https://cdn.babylonjs.com",Xe.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Xe.NoneLogLevel=k.V.NoneLogLevel,Xe.MessageLogLevel=k.V.MessageLogLevel,Xe.WarningLogLevel=k.V.WarningLogLevel,Xe.ErrorLogLevel=k.V.ErrorLogLevel,Xe.AllLogLevel=k.V.AllLogLevel,Xe.IsWindowObjectExist=de.BA,Xe.PerformanceNoneLogLevel=0,Xe.PerformanceUserMarkLogLevel=1,Xe.PerformanceConsoleLogLevel=2,Xe.StartPerformanceCounter=Xe._StartPerformanceCounterDisabled,Xe.EndPerformanceCounter=Xe._EndPerformanceCounterDisabled;class He{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(a),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}Xe.Mix=We.zF,Xe.IsExponentOfTwo=We.L8,_.q.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";var Ke=i(321),Ye=i(329);Ke.w.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new Ye.A(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Ke.w.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new Ye.A(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Ke.w.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},Ke.w.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Ke.w.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Ke.w.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class qe{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(qe._UpdatedUbosInFrame[this._name]||(qe._UpdatedUbosInFrame[this._name]=0),qe._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,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(void 0===s){if(this._buffer)return void k.V.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||0!==this.includeOnlyWithLayerMask&&0==(this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._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=Ze.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=he.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=he.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)}))),he.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return ce.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=Ze.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=he.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);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)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===Ze.INTENSITYMODE_AUTOMATIC&&(i=t===Ze.LIGHTTYPEID_DIRECTIONALLIGHT?Ze.INTENSITYMODE_ILLUMINANCE:Ze.INTENSITYMODE_LUMINOUSINTENSITY),t){case Ze.LIGHTTYPEID_POINTLIGHT:case Ze.LIGHTTYPEID_SPOTLIGHT:switch(i){case Ze.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Ze.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Ze.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Ze.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Ze.INTENSITYMODE_ILLUMINANCE:e=1;break;case Ze.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case Ze.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Ze.FALLOFF_DEFAULT=je.FALLOFF_DEFAULT,Ze.FALLOFF_PHYSICAL=je.FALLOFF_PHYSICAL,Ze.FALLOFF_GLTF=je.FALLOFF_GLTF,Ze.FALLOFF_STANDARD=je.FALLOFF_STANDARD,Ze.LIGHTMAP_DEFAULT=je.LIGHTMAP_DEFAULT,Ze.LIGHTMAP_SPECULAR=je.LIGHTMAP_SPECULAR,Ze.LIGHTMAP_SHADOWSONLY=je.LIGHTMAP_SHADOWSONLY,Ze.INTENSITYMODE_AUTOMATIC=je.INTENSITYMODE_AUTOMATIC,Ze.INTENSITYMODE_LUMINOUSPOWER=je.INTENSITYMODE_LUMINOUSPOWER,Ze.INTENSITYMODE_LUMINOUSINTENSITY=je.INTENSITYMODE_LUMINOUSINTENSITY,Ze.INTENSITYMODE_ILLUMINANCE=je.INTENSITYMODE_ILLUMINANCE,Ze.INTENSITYMODE_LUMINANCE=je.INTENSITYMODE_LUMINANCE,Ze.LIGHTTYPEID_POINTLIGHT=je.LIGHTTYPEID_POINTLIGHT,Ze.LIGHTTYPEID_DIRECTIONALLIGHT=je.LIGHTTYPEID_DIRECTIONALLIGHT,Ze.LIGHTTYPEID_SPOTLIGHT=je.LIGHTTYPEID_SPOTLIGHT,Ze.LIGHTTYPEID_HEMISPHERICLIGHT=je.LIGHTTYPEID_HEMISPHERICLIGHT,z([Z()],Ze.prototype,"diffuse",void 0),z([Z()],Ze.prototype,"specular",void 0),z([q()],Ze.prototype,"falloffType",void 0),z([q()],Ze.prototype,"intensity",void 0),z([q()],Ze.prototype,"range",null),z([q()],Ze.prototype,"intensityMode",null),z([q()],Ze.prototype,"radius",null),z([q()],Ze.prototype,"_renderPriority",void 0),z([Y("_reorderLightsInScene")],Ze.prototype,"renderPriority",void 0),z([q("shadowEnabled")],Ze.prototype,"_shadowEnabled",void 0),z([q("excludeWithLayerMask")],Ze.prototype,"_excludeWithLayerMask",void 0),z([q("includeOnlyWithLayerMask")],Ze.prototype,"_includeOnlyWithLayerMask",void 0),z([q("lightmapMode")],Ze.prototype,"_lightmapMode",void 0);class Qe{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^(0|this.height),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 Qe(this.width*e,this.height*t)}clone(){return new Qe(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Qe(0,0)}add(e){return new Qe(this.width+e.width,this.height+e.height)}subtract(e){return new Qe(this.width-e.width,this.height-e.height)}scale(e){return new Qe(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new Qe(s,r)}}class $e{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}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}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=Qe.Zero(),this._cachedBaseSize=Qe.Zero(),this._initialSamplingMode=2,this._texture=$e._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}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._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):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,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)}}i(212);class Je extends $e{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.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}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.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}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=ze()),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=Je.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 se.cP,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Je._IsScene(e)?this._scene=e:this._engine=e:this._scene=_.q.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 y.IdentityReadOnly}getReflectionTextureMatrix(){return y.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!r,t),h=a.getLoadedTexturesCache();for(let a=0;a=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,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=he.Serialize(this);return he.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}Je.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,z([q()],Je.prototype,"uniqueId",void 0),z([q()],Je.prototype,"name",void 0),z([q()],Je.prototype,"metadata",void 0),z([q("hasAlpha")],Je.prototype,"_hasAlpha",void 0),z([q("getAlphaFromRGB")],Je.prototype,"_getAlphaFromRGB",void 0),z([q()],Je.prototype,"level",void 0),z([q("coordinatesIndex")],Je.prototype,"_coordinatesIndex",void 0),z([q()],Je.prototype,"optimizeUVAllocation",void 0),z([q("coordinatesMode")],Je.prototype,"_coordinatesMode",void 0),z([q()],Je.prototype,"wrapU",null),z([q()],Je.prototype,"wrapV",null),z([q()],Je.prototype,"wrapR",void 0),z([q()],Je.prototype,"anisotropicFilteringLevel",void 0),z([q()],Je.prototype,"isCube",null),z([q()],Je.prototype,"is3D",null),z([q()],Je.prototype,"is2DArray",null),z([q()],Je.prototype,"gammaSpace",null),z([q()],Je.prototype,"invertZ",void 0),z([q()],Je.prototype,"lodLevelInAlpha",void 0),z([q()],Je.prototype,"lodGenerationOffset",null),z([q()],Je.prototype,"lodGenerationScale",null),z([q()],Je.prototype,"linearSpecularLOD",null),z([j()],Je.prototype,"irradianceTexture",null),z([q()],Je.prototype,"isRenderTarget",void 0);class et{constructor(e,t,i,s){this.normal=new M(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new et(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^(0|this.d),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 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=et._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,o=s*i[0]+r*i[1]+n*i[2]+a*i[3],h=s*i[4]+r*i[5]+n*i[6]+a*i[7],l=s*i[8]+r*i[9]+n*i[10]+a*i[11],c=s*i[12]+r*i[13]+n*i[14]+a*i[15];return new et(o,h,l,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,a=i.x-e.x,o=i.y-e.y,h=i.z-e.z,l=r*h-n*o,c=n*a-s*h,d=s*o-r*a,u=Math.sqrt(l*l+c*c+d*d);let f;return f=0!==u?1/u:0,this.normal.x=l*f,this.normal.y=c*f,this.normal.z=d*f,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return M.Dot(this.normal,e)<=t}signedDistanceTo(e){return M.Dot(e,this.normal)+this.d}static FromArray(e){return new et(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new et(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new et(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 M.Dot(i,t)+s}}function tt(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const a=n.getContext("2d");if(!a)return null;const o=a.createImageData(s,r);if(o.data.set(e),a.putImageData(o,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}et._TmpMatrix=y.Identity();class it{}it.UseOpenGLOrientationForUV=!1;class st extends Je{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=st.TRILINEAR_SAMPLINGMODE,a={},o,h=5){throw(0,re.n)("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,r=st.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,h=!1,l,c,d,u,f){let _;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 se.cP,this._isBlocking=!0,this.name=e||"",this.url=e;let p=!1,g=null,m=!0;"object"==typeof i&&null!==i?(_=i.noMipmap??!1,s=i.invertY??!it.UseOpenGLOrientationForUV,r=i.samplingMode??st.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,a=i.onError??null,o=i.buffer??null,h=i.deleteBuffer??!1,l=i.format,c=i.mimeType,d=i.loaderOptions,u=i.creationFlags,p=i.useSRGBBuffer??!1,g=i.internalTexture??null,m=i.gammaSpace??m):_=!!i,this._gammaSpace=m,this._noMipmap=_,this._invertY=void 0===s?!it.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=o,this._deleteBuffer=h,this._mimeType=c,this._loaderOptions=d,this._creationFlags=u,this._useSRGBBuffer=p,this._forcedExtension=f,l&&(this._format=l);const T=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const E=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&T&&T.resetCachedMaterial()},v=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),st.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!g)return this._delayedOnLoad=E,void(this._delayedOnError=v);if(this._texture=g??this._getFromCache(this.url,_,r,this._invertY,p,this.isCube),this._texture)if(this._texture.isReady)Me.SetImmediate((()=>E()));else{const e=this._texture.onLoadedObservable.add(E);this._texture.onErrorObservable.add((t=>{v(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(T&&T.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=E,this._delayedOnError=v;else{try{this._texture=x.createTexture(this.url,_,this._invertY,T,r,E,v,this._buffer,void 0,this._format,this._forcedExtension,c,d,u,p)}catch(e){throw v("error loading",e),e}h&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.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(4!==this.delayLoadState)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?Me.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,M.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=y.Zero(),this._rowGenerationMatrix=new y,this._t0=M.Zero(),this._t1=M.Zero(),this._t2=M.Zero()),y.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(y.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,R.Matrix[0]),y.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,R.Matrix[1]),y.ScalingToRef(this._cachedUScale,this._cachedVScale,0,R.Matrix[2]),y.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,R.Matrix[3]),R.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(R.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(R.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(R.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),y.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,(e=>e.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!==st.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=y.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=y.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 st.PLANAR_MODE:y.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 st.PROJECTION_MODE:{y.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:y.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.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 he.Clone((()=>new st(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;st.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(st._SerializeInternalTextureUniqueId);return t?((st.SerializeBuffers||st.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(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,"+Ee(this._buffer):(st.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?tt(r,e.getSize(),s.invertY):null}(this):async function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?tt(r,e.getSize(),s.invertY):null}(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,st._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=Ge.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return st._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=st._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=et.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(a)}),e._creationFlags??0,e._useSRGBBuffer??!1),a.name=e.name;else{let o;o=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||st.UseSerializedUrlIfAny)&&(o=e.url);const h={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(a)},internalTexture:r};a=new st(o,t,h)}return a}}),e,t)}static CreateFromBase64String(e,t,i,s,r,n=st.TRILINEAR_SAMPLINGMODE,a=null,o=null,h=5,l,c){return new st("data:"+t,i,s,r,n,a,o,e,!1,h,void 0,void 0,l,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,a=st.TRILINEAR_SAMPLINGMODE,o=null,h=null,l=5,c,d){return"data:"!==e.substr(0,5)&&(e="data:"+e),new st(e,i,r,n,a,o,h,t,s,l,void 0,void 0,c,d)}}st.SerializeBuffers=!0,st.ForceSerializeBuffers=!1,st.OnTextureLoadErrorObservable=new se.cP,st._SerializeInternalTextureUniqueId=!1,st._CubeTextureParser=(e,t,i)=>{throw(0,re.n)("CubeTexture")},st._CreateMirror=(e,t,i,s)=>{throw(0,re.n)("MirrorTexture")},st._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw(0,re.n)("RenderTargetTexture")},st.NEAREST_SAMPLINGMODE=1,st.NEAREST_NEAREST_MIPLINEAR=8,st.BILINEAR_SAMPLINGMODE=2,st.LINEAR_LINEAR_MIPNEAREST=11,st.TRILINEAR_SAMPLINGMODE=3,st.LINEAR_LINEAR_MIPLINEAR=3,st.NEAREST_NEAREST_MIPNEAREST=4,st.NEAREST_LINEAR_MIPNEAREST=5,st.NEAREST_LINEAR_MIPLINEAR=6,st.NEAREST_LINEAR=7,st.NEAREST_NEAREST=1,st.LINEAR_NEAREST_MIPNEAREST=9,st.LINEAR_NEAREST_MIPLINEAR=10,st.LINEAR_LINEAR=2,st.LINEAR_NEAREST=12,st.EXPLICIT_MODE=0,st.SPHERICAL_MODE=1,st.PLANAR_MODE=2,st.CUBIC_MODE=3,st.PROJECTION_MODE=4,st.SKYBOX_MODE=5,st.INVCUBIC_MODE=6,st.EQUIRECTANGULAR_MODE=7,st.FIXED_EQUIRECTANGULAR_MODE=8,st.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,st.CLAMP_ADDRESSMODE=0,st.WRAP_ADDRESSMODE=1,st.MIRROR_ADDRESSMODE=2,st.UseSerializedUrlIfAny=!1,z([q()],st.prototype,"url",void 0),z([q()],st.prototype,"uOffset",void 0),z([q()],st.prototype,"vOffset",void 0),z([q()],st.prototype,"uScale",void 0),z([q()],st.prototype,"vScale",void 0),z([q()],st.prototype,"uAng",void 0),z([q()],st.prototype,"vAng",void 0),z([q()],st.prototype,"wAng",void 0),z([q()],st.prototype,"uRotationCenter",void 0),z([q()],st.prototype,"vRotationCenter",void 0),z([q()],st.prototype,"wRotationCenter",void 0),z([q()],st.prototype,"homogeneousRotationInUVTransform",void 0),z([q()],st.prototype,"isBlocking",null),d("BABYLON.Texture",st),he._TextureParser=st.Parse;class rt{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[G.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[G.PositionKind]=new G(this._scene.getEngine(),e,G.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[G.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const a=this._scene.getEngine();for(let o=0;onull!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let o=0,h=s.length;othis.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}nt._GlobalId=0;class at extends nt{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||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));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){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(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(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]: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=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.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(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==ct.G.Depth&&n!==ct.G.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const a=[],o=[],h=[],l=[],c=[],d=[],u=[],f={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,s)}n._bindUnboundFramebuffer(a)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===a.format?d=i.DEPTH_COMPONENT16:16===a.format?d=i.DEPTH_COMPONENT24:17===a.format||13===a.format?d=i.DEPTH24_STENCIL8:14===a.format?d=i.DEPTH_COMPONENT32F:18===a.format&&(d=i.DEPTH32F_STENCIL8)),a.is2DArray?i.texImage3D(n,0,d,a.width,a.height,s,0,c,l,null):a.is3D?i.texImage3D(n,0,d,a.width,a.height,r,0,c,l,null):i.texImage2D(n,0,d,a.width,a.height,0,c,l,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),a},Ke.w.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},Ke.w.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const a=t.width||t,o=t.height||t,h=t.layers||0,l=t.depth||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=h>0,e.depth=h||l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,d=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(d,c.TEXTURE_MAG_FILTER,u.mag),c.texParameteri(d,c.TEXTURE_MIN_FILTER,u.min),c.texParameteri(d,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(d,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(d,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(d,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(d,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(d,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))},Ke.w.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new ct.h(this,ct.G.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const a=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,k.V.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i},Ke.w.prototype.setDepthStencilTexture=function(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))};class ft{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new ft(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 ft(this.x,this.y,this.width,this.height)}}var _t=i(420);class pt{static GetEffect(e){return void 0===e.getPipelineContext?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){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}var gt=i(229);gt.l.ShadersStore.postprocessVertexShader="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}";const mt={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Tt{constructor(e,t=mt){this._fullscreenViewport=new ft(0,0,1,1);const i=t.positions??mt.positions,s=t.indices??mt.indices;this.engine=e,this._vertexBuffers={[G.PositionKind]:new G(e,i,G.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._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 void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?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[G.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[G.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class xt{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new se.cP;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new pt(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new _t.M(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Et="passPixelShader",vt="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";gt.l.ShadersStore[Et]=vt;const At=Et,Mt=vt;class bt{static _CreateDumpRenderer(){if(!bt._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Ke.w(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new Ke.w(e,!1,i)}_.q.Instances.pop(),_.q.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===_.q.Instances.length&&bt.Dispose()})),t.getCaps().parallelShaderCompile=void 0;const s=new Tt(t),r=new xt({engine:t,name:At,fragmentShader:Mt,samplerNames:["textureSampler"]});bt._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return bt._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,a){const o=await i.readPixels(0,0,e,t),h=new Uint8Array(o.buffer);bt.DumpData(e,t,h,s,r,n,!0,void 0,a)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,a=!1,o){return new Promise((h=>{bt.DumpData(e,t,i,(e=>h(e)),s,r,n,a,o)}))}static DumpData(e,t,i,s,r="image/png",n,a=!1,o=!1,h){const l=bt._CreateDumpRenderer();if(l.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*P.Clamp(s))}i=e}const c=l.engine.createRawTexture(i,e,t,5,!1,!a,1);l.renderer.setViewport(),l.renderer.applyEffectWrapper(l.wrapper),l.wrapper.effect._bindTexture("textureSampler",c),l.renderer.draw(),o?Xe.ToBlob(l.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,h):Xe.EncodeScreenshotCanvasData(l.canvas,s,r,n,h),c.dispose()}static Dispose(){bt._DumpToolsEngine&&(bt._DumpToolsEngine.wrapper.dispose(),bt._DumpToolsEngine.renderer.dispose(),bt._DumpToolsEngine.engine.dispose()),bt._DumpToolsEngine=null}}Xe.DumpData=bt.DumpData,Xe.DumpDataAsync=bt.DumpDataAsync,Xe.DumpFramebuffer=bt.DumpFramebuffer,_t.M.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class St extends st{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=l(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new se.cP,this.onAfterUnbindObservable=new se.cP,this.onBeforeRenderObservable=new se.cP,this.onAfterRenderObservable=new se.cP,this.onClearObservable=new se.cP,this.onResizeObservable=new se.cP,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=M.Zero(),!(i=this.getScene()))return;const x=this.getScene().getEngine();this._gammaSpace=T,this._coordinatesMode=st.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new lt(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:l,samples:f,creationFlags:_,noColorAttachment:p,useSRGBBuffer:g,colorAttachment:m,label:this.name},this.samplingMode===st.NEAREST_SAMPLINGMODE&&(this.wrapU=st.CLAMP_ADDRESSMODE,this.wrapV=st.CLAMP_ADDRESSMODE),u||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=st.INVCUBIC_MODE,this._textureMatrix=y.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==f&&(this.samples=f)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||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){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const a=n.getEngine();if(a._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(a.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(a.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),a.snapshotRendering&&1===a.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let o=null;const h=this.renderList?this.renderList:n.getActiveMeshes().data,l=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(o=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,h,l)),o?this._prepareRenderingManager(o,o.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(h,l,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),o=h);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,o,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&bt.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),a)}this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&5===e&&a.generateMipMapsForCubemap(this._texture,!0),a._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new St(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 i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===St.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=St.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}St.REFRESHRATE_RENDER_ONCE=0,St.REFRESHRATE_RENDER_ONEVERYFRAME=1,St.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,st._CreateRenderTargetTexture=(e,t,i,s,r)=>new St(e,t,i,s);var yt=i(662);s.$.prototype.setTextureFromPostProcess=function(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)},s.$.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},_t.M.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},_t.M.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class It{static RegisterShaderCodeProcessing(e,t){t?It._CustomShaderCodeProcessing[e??""]=t:delete It._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return It._CustomShaderCodeProcessing[e]??It._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,a=1,o,h,l=null,c=0,d="postprocess",u,f=!1,_=5,p=yt.w.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new nt(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new A(1,1),this._texelSize=A.Zero(),this.onActivateObservable=new se.cP,this.onSizeChangedObservable=new se.cP,this.onApplyObservable=new se.cP,this.onBeforeRenderObservable=new se.cP,this.onAfterRenderObservable=new se.cP,this.name=e;let g=1,m=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,g=e.size??1,n=e.camera??null,a=e.samplingMode??1,o=e.engine,h=e.reusable,l=e.defines??null,c=e.textureType??0,d=e.vertexUrl??"postprocess",u=e.indexParameters,f=e.blockCompilation??!1,_=e.textureFormat??5,p=e.shaderLanguage??yt.w.GLSL,m=e.uniformBuffers??null}else r&&(g="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=g,this.renderTargetSamplingMode=a||1,this._reusable=h||!1,this._textureType=c,this._textureFormat=_,this._shaderLanguage=p,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=m||[],this._indexParameters=u,this._drawWrapper=new pt(this._engine),f||this.updateEffect(l)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new nt(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,a,o){const h=It._GetShaderCodeProcessing(this.name);if(h?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=h.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:a??this._vertexUrl,fragment:o??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:h?.processCodeAfterIncludes?(e,t)=>h.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:h?.processFinalCode?(e,t)=>h.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return d||(d=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(a/h,o/l),this._engine.bindFramebuffer(d,0,a,o,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(d,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),d}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),It._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(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)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=he.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=It.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=u(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return he.Parse((()=>new It(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)}}It._CustomShaderCodeProcessing={},z([q()],It.prototype,"uniqueId",void 0),z([q()],It.prototype,"name",void 0),z([q()],It.prototype,"width",void 0),z([q()],It.prototype,"height",void 0),z([q()],It.prototype,"renderTargetSamplingMode",void 0),z([te()],It.prototype,"clearColor",void 0),z([q()],It.prototype,"autoClear",void 0),z([q()],It.prototype,"forceAutoClearInAlphaMode",void 0),z([q()],It.prototype,"alphaMode",void 0),z([q()],It.prototype,"alphaConstants",void 0),z([q()],It.prototype,"enablePixelPerfectMode",void 0),z([q()],It.prototype,"forceFullscreenViewport",void 0),z([q()],It.prototype,"scaleMode",void 0),z([q()],It.prototype,"alwaysForcePOT",void 0),z([q("samples")],It.prototype,"_samples",void 0),z([q()],It.prototype,"adaptScaleToCurrentViewport",void 0),d("BABYLON.PostProcess",It);gt.l.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";gt.l.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";gt.l.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";gt.l.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";gt.l.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";gt.l.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";gt.l.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Rt extends It{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=st.BILINEAR_SAMPLINGMODE,a,o,h=0,l="",c=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,a,o,null,h,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=l,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],a=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return he.Parse((()=>new Rt(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}z([q("kernel")],Rt.prototype,"_kernel",void 0),z([q("packedFloat")],Rt.prototype,"_packedFloat",void 0),z([$()],Rt.prototype,"direction",void 0),d("BABYLON.BlurPostProcess",Rt);class Ct{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i=0){const e=i.activeCamera;1===e.mode&&k.V.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function Bt(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(wt,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",wt)):i.setColor3("vFogColor",e.fogColor))}function Ut(e,t,i){Lt.NUM_MORPH_INFLUENCERS=i,kt(e,t,Lt)}function kt(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&_.q.LastCreatedEngine){const r=_.q.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const a=n&&n.supportsNormals&&i.NORMAL,o=n&&n.supportsTangents&&i.TANGENT,h=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&k.V.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Vt(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function Gt(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function zt(e,t){t.bindToEffect(e,"Scene")}function Wt(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function Xt(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function Ht(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function Kt(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function Yt(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function qt(e,t,i,s,r,n,a){switch(a.needNormals=!0,void 0===r["LIGHT"+s]&&(a.needRebuild=!0),r["LIGHT"+s]=!0,r["SPOTLIGHT"+s]=!1,r["HEMILIGHT"+s]=!1,r["POINTLIGHT"+s]=!1,r["DIRLIGHT"+s]=!1,i.prepareLightSpecificDefines(r,s),r["LIGHT_FALLOFF_PHYSICAL"+s]=!1,r["LIGHT_FALLOFF_GLTF"+s]=!1,r["LIGHT_FALLOFF_STANDARD"+s]=!1,i.falloffType){case je.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+s]=!0;break;case je.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+s]=!0;break;case je.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+s]=!0}if(n&&!i.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+s]=!1,r["SHADOWCSM"+s]=!1,r["SHADOWCSMDEBUG"+s]=!1,r["SHADOWCSMNUM_CASCADES"+s]=!1,r["SHADOWCSMUSESHADOWMAXZ"+s]=!1,r["SHADOWCSMNOBLEND"+s]=!1,r["SHADOWCSM_RIGHTHANDED"+s]=!1,r["SHADOWPCF"+s]=!1,r["SHADOWPCSS"+s]=!1,r["SHADOWPOISSON"+s]=!1,r["SHADOWESM"+s]=!1,r["SHADOWCLOSEESM"+s]=!1,r["SHADOWCUBE"+s]=!1,r["SHADOWLOWQUALITY"+s]=!1,r["SHADOWMEDIUMQUALITY"+s]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){const t=i.getShadowGenerator(e.activeCamera)??i.getShadowGenerator();if(t){const e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=je.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==je.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function jt(e,t,i,s,r=null,n=!1){r&&r.push("Light"+e),n||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowTexture"+e),i.push("depthTexture"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),s&&(i.push("projectionLightTexture"+e),t.push("textureProjectionMatrix"+e)))}class Zt{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===Zt.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===Zt.FILTER_PCF||e===Zt.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==Zt.FILTER_PCF&&e!==Zt.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===Zt.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Zt.FILTER_POISSONSAMPLING);(e||this.filter===Zt.FILTER_POISSONSAMPLING)&&(this.filter=e?t:Zt.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Zt.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Zt.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Zt.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Zt.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Zt.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Zt.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Zt.FILTER_PCF);(e||this.filter===Zt.FILTER_PCF)&&(this.filter=e?t:Zt.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===Zt.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Zt.FILTER_PCSS);(e||this.filter===Zt.FILTER_PCSS)&&(this.filter=e?t:Zt.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return Zt.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new se.cP,this.onAfterShadowMapRenderObservable=new se.cP,this.onBeforeShadowMapRenderMeshObservable=new se.cP,this.onAfterShadowMapRenderMeshObservable=new se.cP,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Zt.FILTER_NONE,this._filteringQuality=Zt.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=M.Zero(),this._viewMatrix=y.Zero(),this._projectionMatrix=y.Zero(),this._transformMatrix=y.Zero(),this._cachedPosition=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=y.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),Zt._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new St(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new St(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=st.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=st.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(st.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===Zt.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Zt.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new N(0,0,0,0),i=new N(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===Zt.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=lt.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new Rt(this._light.name+"KernelBlurY",new A(0,1),this.blurKernel,1,null,st.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new It(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,st.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(l,"Mesh"),s.transferToEffect(e?t:f)):(i.getMeshUniformBuffer().bindToEffect(l,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,a.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(l),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===Zt.FILTER_NONE||this.filter===Zt.FILTER_PCSS?this._shadowMap.updateSamplingMode(st.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(st.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let a=0;const o=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[a],i.useInstances,n[a].getMaterial()?.needAlphaBlendingForMesh(n[a].getMesh())??!1);)if(a++,a>=n.length)return void(e&&e(this));setTimeout(o,16)}};o()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(G.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Ze.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,a=i.defines;const o=[G.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(G.NormalKind)&&(o.push(G.NormalKind),n.push("#define NORMAL"),h.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const l=s.needAlphaTesting();if((l||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??Zt.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),l&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(G.UVKind)&&(o.push(G.UVKind),n.push("#define UV1")),h.isVerticesDataPresent(G.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(o.push(G.UV2Kind),n.push("#define UV2"))}const c=new Ct;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){o.push(G.MatricesIndicesKind),o.push(G.MatricesWeightsKind),h.numBoneInfluencers>4&&(o.push(G.MatricesIndicesExtraKind),o.push(G.MatricesWeightsExtraKind));const e=h.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const d=h.morphTargetManager;let u=0;if(d&&(u=d.numMaxInfluencers||d.numInfluencers,u>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+u),d.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),Ut(o,h,u))),Dt(s,this._scene,n),t&&(n.push("#define INSTANCES"),Vt(o),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const f=h.bakedVertexAnimationManager;t&&f&&f.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),o.push("bakedVertexAnimationSettingsInstanced"));const _=n.join("\n");if(a!==_){a=_;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(Pt(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===o.indexOf(e)&&o.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const h=this._scene.getEngine();r=h.createEffect(e,{attributes:o,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:_,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:u}},h),i.setEffect(r,a)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Zt.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Zt.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Zt.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Zt.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===Zt.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Zt.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),M.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(M.Dot(this._lightDirection,M.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),y.LookAtLHToRef(t,t.add(this._lightDirection),M.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw(0,re.n)("ShadowGeneratorSceneComponent")};class Qt{constructor(e,t,i){this.vectors=o.BuildArray(8,M.Zero),this.center=M.Zero(),this.centerWorld=M.Zero(),this.extendSize=M.Zero(),this.extendSizeWorld=M.Zero(),this.directions=o.BuildArray(3,M.Zero),this.vectorsWorld=o.BuildArray(8,M.Zero),this.minimumWorld=M.Zero(),this.maximumWorld=M.Zero(),this.minimum=M.Zero(),this.maximum=M.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,a=t.x,o=t.y,h=t.z,l=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(a,o,h),l[0].copyFromFloats(s,r,n),l[1].copyFromFloats(a,o,h),l[2].copyFromFloats(a,r,n),l[3].copyFromFloats(s,o,n),l[4].copyFromFloats(s,r,h),l[5].copyFromFloats(a,o,n),l[6].copyFromFloats(s,o,h),l[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||y.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Qt._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),a=this.center.subtractToRef(n,t[1]),o=this.center.addToRef(n,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const a=r[s];M.TransformCoordinatesToRef(n[s],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}M.FromArrayToRef(e.m,0,s[0]),M.FromArrayToRef(e.m,4,s[1]),M.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return Qt.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Qt.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,h=i.y,l=i.z,c=e.x,d=e.y,u=e.z,f=-a;return!(o-cc-s||h-dd-r||l-uu-n)}intersectsSphere(e){return Qt.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,a=i.z,o=s.x,h=s.y,l=s.z,c=e.x,d=e.y,u=e.z,f=t.x,_=t.y,p=t.z;return!(of||h_||lp)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=Qt._TmpVector3[0];return M.ClampToRef(i,e,t,r),M.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}Qt._TmpVector3=o.BuildArray(3,M.Zero);class $t{constructor(e,t,i){this.center=M.Zero(),this.centerWorld=M.Zero(),this.minimum=M.Zero(),this.maximum=M.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=M.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||y.IdentityReadOnly)}scale(e){const t=this.radius*e,i=$t._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{M.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=$t._TmpVector3[0];M.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=M.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=M.Dot(t.centerWorld,e),r=Math.abs(M.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(M.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(M.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},ii=(e,t,i)=>(ti(e,t,Jt),ti(e,i,ei),!(Jt.min>ei.max||ei.min>Jt.max));class si{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Qt(e,t,i),this.boundingSphere=new $t(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=si._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=si._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=M.Minimize(this.minimum,e),i=M.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=R.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=R.Vector3[0];return M.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),M.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!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,si._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(!$t.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!Qt.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(ii(i.directions[0],i,s)&&ii(i.directions[1],i,s)&&ii(i.directions[2],i,s)&&ii(s.directions[0],i,s)&&ii(s.directions[1],i,s)&&ii(s.directions[2],i,s)&&ii(M.Cross(i.directions[0],s.directions[0]),i,s)&&ii(M.Cross(i.directions[0],s.directions[1]),i,s)&&ii(M.Cross(i.directions[0],s.directions[2]),i,s)&&ii(M.Cross(i.directions[1],s.directions[0]),i,s)&&ii(M.Cross(i.directions[1],s.directions[1]),i,s)&&ii(M.Cross(i.directions[1],s.directions[2]),i,s)&&ii(M.Cross(i.directions[2],s.directions[0]),i,s)&&ii(M.Cross(i.directions[2],s.directions[1]),i,s)&&ii(M.Cross(i.directions[2],s.directions[2]),i,s))}}si._TmpVector3=o.BuildArray(2,M.Zero);class ri{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new et(0,0,0,0));return ri.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){ri.GetNearPlaneToRef(e,t[0]),ri.GetFarPlaneToRef(e,t[1]),ri.GetLeftPlaneToRef(e,t[2]),ri.GetRightPlaneToRef(e,t[3]),ri.GetTopPlaneToRef(e,t[4]),ri.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class ni extends ce{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===ni.PERSPECTIVE_CAMERA)this.fovMode===ni.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}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=M.Zero(),this._upVector=M.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=ni.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new ft(0,0,1,1),this.layerMask=268435455,this.fovMode=ni.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ni.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new se.cP,this.onProjectionMatrixChangedObservable=new se.cP,this.onAfterCheckInputsObservable=new se.cP,this.onRestoreStateObservable=new se.cP,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new y,this._postProcesses=new Array,this._activeMeshes=new nt(256),this._globalPosition=M.Zero(),this._computedViewMatrix=y.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=y.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=S.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(k.V.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?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);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return y.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){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===ni.PERSPECTIVE_CAMERA){let e;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),e=i.useRightHandedSystem?y.PerspectiveFovRHToRef:y.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ni.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?y.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,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):y.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?y.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,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):y.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,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=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.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){return(this.radius||(this.target?M.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?ri.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ri.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,re.n)("Ray")}getForwardRayToRef(e,t=100,i,s){throw(0,re.n)("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 e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==ni.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.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 e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Xe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ni.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return y.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,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Xe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eni._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=ni.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=he.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=M.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(M.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(M.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw(0,re.n)("UniversalCamera")},ni.PERSPECTIVE_CAMERA=0,ni.ORTHOGRAPHIC_CAMERA=1,ni.FOVMODE_VERTICAL_FIXED=0,ni.FOVMODE_HORIZONTAL_FIXED=1,ni.RIG_MODE_NONE=0,ni.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,ni.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,ni.RIG_MODE_STEREOSCOPIC_INTERLACED=14,ni.RIG_MODE_VR=20,ni.RIG_MODE_CUSTOM=22,ni.ForceAttachControlToAlwaysPreventDefault=!1,z([J("position")],ni.prototype,"_position",void 0),z([J("upVector")],ni.prototype,"_upVector",void 0),z([q()],ni.prototype,"orthoLeft",null),z([q()],ni.prototype,"orthoRight",null),z([q()],ni.prototype,"orthoBottom",null),z([q()],ni.prototype,"orthoTop",null),z([q()],ni.prototype,"fov",void 0),z([q()],ni.prototype,"projectionPlaneTilt",void 0),z([q()],ni.prototype,"minZ",void 0),z([q()],ni.prototype,"maxZ",void 0),z([q()],ni.prototype,"inertia",void 0),z([q()],ni.prototype,"mode",null),z([q()],ni.prototype,"layerMask",void 0),z([q()],ni.prototype,"fovMode",void 0),z([q()],ni.prototype,"cameraRigMode",void 0),z([q()],ni.prototype,"interaxialDistance",void 0),z([q()],ni.prototype,"isStereoscopicSideBySide",void 0);gt.l.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";gt.l.IncludesShadersStore.instancesDeclaration="#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#ifdef INSTANCESCOLOR\nattribute vec4 instanceColor;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;\n#ifdef THIN_INSTANCES\nuniform mat4 previousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform mat4 previousWorld;\n#endif\n#endif\n";gt.l.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";gt.l.IncludesShadersStore.pointCloudVertex="#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n";gt.l.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class ai{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=st.TRILINEAR_SAMPLINGMODE,n=!1,a){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new N(1,1,1,1):this.clearColor=new N(n?1e8:1,0,0,1),ai._SceneComponentInitialization(this._scene);const o=e.getEngine();this._camera=i,r!==st.NEAREST_SAMPLINGMODE&&(1!==t||o._caps.textureFloatLinearFiltering||(r=st.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(r=st.NEAREST_SAMPLINGMODE));const h=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new St(a??"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,h),this._depthMap.wrapU=st.CLAMP_ADDRESSMODE,this._depthMap.wrapV=st.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{o._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{o._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const a=i._getWorldMatrixDeterminant()<0;let o=t.overrideMaterialSideOrientation??n.sideOrientation;a&&(o=0===o?1:0);const h=0===o;r.setState(n.backFaceCulling,0,!1,h,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const l=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(l.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==l.visibleInstances[e._id]&&void 0!==l.visibleInstances[e._id]||t.hasThinInstances),d=this._camera||s.activeCamera;if(this.isReady(e,c)&&d){e._renderId=s.getRenderId();const a=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let o=e._getDrawWrapper();!o&&a&&(o=a._getDrawWrapper());const h=d.mode===ni.ORTHOGRAPHIC_CAMERA;if(!o)return;const u=o.effect;let f,_;if(r.enableEffect(o),c||t._bind(e,u,n.fillMode),a?a.bindForSubMesh(i.getWorldMatrix(),i,e):(u.setMatrix("viewProjection",s.getTransformMatrix()),u.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&u.setMatrix("view",s.getViewMatrix())),h?(f=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(f=r.useReverseDepthBuffer&&r.isNDCHalfZRange?d.minZ:r.isNDCHalfZRange?0:d.minZ,_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:d.maxZ),u.setFloat2("depthValues",f,f+_),!a){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(u.setTexture("diffuseSampler",e),u.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;u.setTexture("boneSampler",i),u.setFloat("boneTextureWidth",4*(e.bones.length+1))}else u.setMatrices("mBones",e.getTransformMatrices(t))}Ot(u,n,s),Gt(t,u),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(u),n.pointsCloud&&u.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,u,n.fillMode,l,c,((e,t)=>u.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(h.push(G.MatricesIndicesExtraKind),h.push(G.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),o.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&o.push("#define BONETEXTURE")}else o.push("#define NUM_BONE_INFLUENCERS 0");const l=s.morphTargetManager;let c=0;l&&(c=l.numMaxInfluencers||l.numInfluencers,c>0&&(o.push("#define MORPHTARGETS"),o.push("#define NUM_MORPH_INFLUENCERS "+c),l.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),Ut(h,s,c))),a.pointsCloud&&o.push("#define POINTSIZE"),t&&(o.push("#define INSTANCES"),Vt(h),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&o.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&o.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&o.push("#define PACKED"),Dt(a,r,o);const d=e._getDrawWrapper(void 0,!0),u=d.defines,f=o.join("\n");if(u!==f){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Pt(e),d.setEffect(i.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),f)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}ai._SceneComponentInitialization=e=>{throw(0,re.n)("DepthRendererSceneComponent")};gt.l.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class oi{constructor(e){this.onAfterReductionPerformed=new se.cP,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new rt(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new It("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let a=this._sourceTexture.getRenderWidth(),o=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(a,o),this._reductionSteps.push(n);let h=1;for(;a>1||o>1;){a=Math.max(Math.round(a/2),1),o=Math.max(Math.round(o/2),1);const e=new It("Reduction phase "+h,"minmaxRedux",["texSize"],null,{width:a,height:o},null,1,r.getEngine(),!1,"#define "+(1==a&&1==o?"LAST":1==a||1==o?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(a,o),this._reductionSteps.push(e),h++,1==a&&1==o){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(a,o,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return _i.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,a=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,o=a-n,h=a/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Zt.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Zt.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Zt.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===Zt.FILTER_PCSS){for(let e=0;enew _i(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}_i._FrustumCornersNDCSpace=[new M(-1,1,-1),new M(1,1,-1),new M(1,-1,-1),new M(-1,-1,-1),new M(-1,1,1),new M(1,1,1),new M(1,-1,1),new M(-1,-1,1)],_i.CLASSNAME="CascadedShadowGenerator",_i.DEFAULT_CASCADES_COUNT=4,_i.MIN_CASCADES_COUNT=2,_i.MAX_CASCADES_COUNT=4,_i._SceneComponentInitialization=e=>{throw(0,re.n)("ShadowGeneratorSceneComponent")};class pi{}pi.NAME_EFFECTLAYER="EffectLayer",pi.NAME_LAYER="Layer",pi.NAME_LENSFLARESYSTEM="LensFlareSystem",pi.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",pi.NAME_PARTICLESYSTEM="ParticleSystem",pi.NAME_GAMEPAD="Gamepad",pi.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",pi.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",pi.NAME_PREPASSRENDERER="PrePassRenderer",pi.NAME_DEPTHRENDERER="DepthRenderer",pi.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",pi.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",pi.NAME_SPRITE="Sprite",pi.NAME_SUBSURFACE="SubSurface",pi.NAME_OUTLINERENDERER="Outline",pi.NAME_PROCEDURALTEXTURE="ProceduralTexture",pi.NAME_SHADOWGENERATOR="ShadowGenerator",pi.NAME_OCTREE="Octree",pi.NAME_PHYSICSENGINE="PhysicsEngine",pi.NAME_AUDIO="Audio",pi.NAME_FLUIDRENDERER="FluidRenderer",pi.STEP_ISREADYFORMESH_EFFECTLAYER=0,pi.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,pi.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,pi.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,pi.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,pi.STEP_BEFORECAMERADRAW_PREPASS=0,pi.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,pi.STEP_BEFORECAMERADRAW_LAYER=2,pi.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,pi.STEP_BEFORERENDERTARGETDRAW_LAYER=1,pi.STEP_BEFORERENDERINGMESH_PREPASS=0,pi.STEP_BEFORERENDERINGMESH_OUTLINE=1,pi.STEP_AFTERRENDERINGMESH_PREPASS=0,pi.STEP_AFTERRENDERINGMESH_OUTLINE=1,pi.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,pi.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,pi.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,pi.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,pi.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,pi.STEP_BEFORECLEAR_PREPASS=1,pi.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,pi.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,pi.STEP_AFTERRENDERTARGETDRAW_LAYER=1,pi.STEP_AFTERCAMERADRAW_PREPASS=0,pi.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,pi.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,pi.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,pi.STEP_AFTERCAMERADRAW_LAYER=4,pi.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,pi.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,pi.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,pi.STEP_AFTERRENDER_AUDIO=0,pi.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,pi.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,pi.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,pi.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,pi.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,pi.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,pi.STEP_POINTERMOVE_SPRITE=0,pi.STEP_POINTERDOWN_SPRITE=0,pi.STEP_POINTERUP_SPRITE=0;class gi extends Array{constructor(e){super(...e)}static Create(){return Object.create(gi.prototype)}registerStep(e,t,i){let s=0,r=Number.MAX_VALUE;for(;se=e.concat(t.bones))),e}}mi._BabylonFileParsers={},mi._IndividualBabylonFileParsers={},d("BABYLON.AbstractScene",mi),mi.AddParser(pi.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;it.length)return void k.V.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,a=!1,o=!1;switch(s.image_type){case 9:n=!0;case 1:a=!0;break;case 10:n=!0;case 2:break;case 11:n=!0;case 3:o=!0}const h=s.pixel_size>>3,l=s.width*s.height*h;let c,d,u,f,_,p,g;if(a&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(l);let a=0;const o=new Uint8Array(h);for(;i>4){default:case 2:d=0,f=1,g=s.width,u=0,_=1,p=s.height;break;case 0:d=0,f=1,g=s.width,u=s.height-1,_=-1,p=-1;break;case 3:d=s.width-1,f=-1,g=-1,u=0,_=1,p=s.height;break;case 1:d=s.width-1,f=-1,g=-1,u=s.height-1,_=-1,p=-1}const m="_getImageData"+(o?"Grey":"")+s.pixel_size+"bits",T=vi[m](s,c,r,u,_,p,d,f,g);e.getEngine()._uploadDataToTextureDirectly(e,T)}Zt._SceneComponentInitialization=e=>{let t=e._getComponent(pi.NAME_SHADOWGENERATOR);t||(t=new Ti(e),e._addComponent(t))};const vi={GetTGAHeader:xi,UploadContent:Ei,_getImageData8bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=t,d=e.width,u=e.height;let f,_,p,g=0;const m=new Uint8Array(d*u*4);for(p=s;p!==n;p+=r)for(_=a;_!==h;_+=o,g++)f=l[g],m[4*(_+d*p)+3]=255,m[4*(_+d*p)+2]=c[3*f+0],m[4*(_+d*p)+1]=c[3*f+1],m[4*(_+d*p)+0]=c[3*f+2];return m},_getImageData16bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_,p=0;const g=new Uint8Array(c*d*4);for(_=s;_!==n;_+=r)for(f=a;f!==h;f+=o,p+=2){u=l[p+0]+(l[p+1]<<8);const e=255*((31744&u)>>10)/31|0,t=255*((992&u)>>5)/31|0,i=255*(31&u)/31|0;g[4*(f+c*_)+0]=e,g[4*(f+c*_)+1]=t,g[4*(f+c*_)+2]=i,g[4*(f+c*_)+3]=32768&u?0:255}return g},_getImageData24bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_=0;const p=new Uint8Array(c*d*4);for(f=s;f!==n;f+=r)for(u=a;u!==h;u+=o,_+=3)p[4*(u+c*f)+3]=255,p[4*(u+c*f)+2]=l[_+0],p[4*(u+c*f)+1]=l[_+1],p[4*(u+c*f)+0]=l[_+2];return p},_getImageData32bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_=0;const p=new Uint8Array(c*d*4);for(f=s;f!==n;f+=r)for(u=a;u!==h;u+=o,_+=4)p[4*(u+c*f)+2]=l[_+0],p[4*(u+c*f)+1]=l[_+1],p[4*(u+c*f)+0]=l[_+2],p[4*(u+c*f)+3]=l[_+3];return p},_getImageDataGrey8bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_,p=0;const g=new Uint8Array(c*d*4);for(_=s;_!==n;_+=r)for(f=a;f!==h;f+=o,p++)u=l[p],g[4*(f+c*_)+0]=u,g[4*(f+c*_)+1]=u,g[4*(f+c*_)+2]=u,g[4*(f+c*_)+3]=255;return g},_getImageDataGrey16bits:function(e,t,i,s,r,n,a,o,h){const l=i,c=e.width,d=e.height;let u,f,_=0;const p=new Uint8Array(c*d*4);for(f=s;f!==n;f+=r)for(u=a;u!==h;u+=o,_+=2)p[4*(u+c*f)+0]=l[_+0],p[4*(u+c*f)+1]=l[_+0],p[4*(u+c*f)+2]=l[_+0],p[4*(u+c*f)+3]=l[_+1];return p}};var Ai=i(610);Ai.N._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=xi(s);i(r.width,r.height,t.generateMipMaps,!1,(()=>{Ei(t,s)}))}});gt.l.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying float vFragmentDepth;\n#endif\n";gt.l.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n";gt.l.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";gt.l.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n";gt.l.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n";class Mi{}Mi.AUTOSAMPLERSUFFIX="Sampler",Mi.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",Mi.ALPHA_DISABLE=0,Mi.ALPHA_ADD=1,Mi.ALPHA_COMBINE=2,Mi.ALPHA_SUBTRACT=3,Mi.ALPHA_MULTIPLY=4,Mi.ALPHA_MAXIMIZED=5,Mi.ALPHA_ONEONE=6,Mi.ALPHA_PREMULTIPLIED=7,Mi.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Mi.ALPHA_INTERPOLATE=9,Mi.ALPHA_SCREENMODE=10,Mi.ALPHA_ONEONE_ONEONE=11,Mi.ALPHA_ALPHATOCOLOR=12,Mi.ALPHA_REVERSEONEMINUS=13,Mi.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Mi.ALPHA_ONEONE_ONEZERO=15,Mi.ALPHA_EXCLUSION=16,Mi.ALPHA_LAYER_ACCUMULATE=17,Mi.ALPHA_EQUATION_ADD=0,Mi.ALPHA_EQUATION_SUBSTRACT=1,Mi.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Mi.ALPHA_EQUATION_MAX=3,Mi.ALPHA_EQUATION_MIN=4,Mi.ALPHA_EQUATION_DARKEN=5,Mi.DELAYLOADSTATE_NONE=0,Mi.DELAYLOADSTATE_LOADED=1,Mi.DELAYLOADSTATE_LOADING=2,Mi.DELAYLOADSTATE_NOTLOADED=4,Mi.NEVER=512,Mi.ALWAYS=519,Mi.LESS=513,Mi.EQUAL=514,Mi.LEQUAL=515,Mi.GREATER=516,Mi.GEQUAL=518,Mi.NOTEQUAL=517,Mi.KEEP=7680,Mi.ZERO=0,Mi.REPLACE=7681,Mi.INCR=7682,Mi.DECR=7683,Mi.INVERT=5386,Mi.INCR_WRAP=34055,Mi.DECR_WRAP=34056,Mi.TEXTURE_CLAMP_ADDRESSMODE=0,Mi.TEXTURE_WRAP_ADDRESSMODE=1,Mi.TEXTURE_MIRROR_ADDRESSMODE=2,Mi.TEXTURE_CREATIONFLAG_STORAGE=1,Mi.TEXTUREFORMAT_ALPHA=0,Mi.TEXTUREFORMAT_LUMINANCE=1,Mi.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Mi.TEXTUREFORMAT_RGB=4,Mi.TEXTUREFORMAT_RGBA=5,Mi.TEXTUREFORMAT_RED=6,Mi.TEXTUREFORMAT_R=6,Mi.TEXTUREFORMAT_RG=7,Mi.TEXTUREFORMAT_RED_INTEGER=8,Mi.TEXTUREFORMAT_R_INTEGER=8,Mi.TEXTUREFORMAT_RG_INTEGER=9,Mi.TEXTUREFORMAT_RGB_INTEGER=10,Mi.TEXTUREFORMAT_RGBA_INTEGER=11,Mi.TEXTUREFORMAT_BGRA=12,Mi.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Mi.TEXTUREFORMAT_DEPTH32_FLOAT=14,Mi.TEXTUREFORMAT_DEPTH16=15,Mi.TEXTUREFORMAT_DEPTH24=16,Mi.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Mi.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Mi.TEXTUREFORMAT_STENCIL8=19,Mi.TEXTUREFORMAT_UNDEFINED=4294967295,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Mi.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Mi.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Mi.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Mi.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Mi.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Mi.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Mi.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Mi.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Mi.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Mi.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Mi.TEXTURETYPE_UNSIGNED_BYTE=0,Mi.TEXTURETYPE_UNSIGNED_INT=0,Mi.TEXTURETYPE_FLOAT=1,Mi.TEXTURETYPE_HALF_FLOAT=2,Mi.TEXTURETYPE_BYTE=3,Mi.TEXTURETYPE_SHORT=4,Mi.TEXTURETYPE_UNSIGNED_SHORT=5,Mi.TEXTURETYPE_INT=6,Mi.TEXTURETYPE_UNSIGNED_INTEGER=7,Mi.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Mi.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Mi.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Mi.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Mi.TEXTURETYPE_UNSIGNED_INT_24_8=12,Mi.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Mi.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Mi.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Mi.TEXTURETYPE_UNDEFINED=16,Mi.TEXTURE_2D=3553,Mi.TEXTURE_2D_ARRAY=35866,Mi.TEXTURE_CUBE_MAP=34067,Mi.TEXTURE_CUBE_MAP_ARRAY=3735928559,Mi.TEXTURE_3D=32879,Mi.TEXTURE_NEAREST_SAMPLINGMODE=1,Mi.TEXTURE_NEAREST_NEAREST=1,Mi.TEXTURE_BILINEAR_SAMPLINGMODE=2,Mi.TEXTURE_LINEAR_LINEAR=2,Mi.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Mi.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Mi.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Mi.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Mi.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Mi.TEXTURE_NEAREST_LINEAR=7,Mi.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Mi.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Mi.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Mi.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Mi.TEXTURE_LINEAR_NEAREST=12,Mi.TEXTURE_EXPLICIT_MODE=0,Mi.TEXTURE_SPHERICAL_MODE=1,Mi.TEXTURE_PLANAR_MODE=2,Mi.TEXTURE_CUBIC_MODE=3,Mi.TEXTURE_PROJECTION_MODE=4,Mi.TEXTURE_SKYBOX_MODE=5,Mi.TEXTURE_INVCUBIC_MODE=6,Mi.TEXTURE_EQUIRECTANGULAR_MODE=7,Mi.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Mi.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Mi.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Mi.TEXTURE_FILTERING_QUALITY_HIGH=64,Mi.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Mi.TEXTURE_FILTERING_QUALITY_LOW=8,Mi.SCALEMODE_FLOOR=1,Mi.SCALEMODE_NEAREST=2,Mi.SCALEMODE_CEILING=3,Mi.MATERIAL_TextureDirtyFlag=1,Mi.MATERIAL_LightDirtyFlag=2,Mi.MATERIAL_FresnelDirtyFlag=4,Mi.MATERIAL_AttributesDirtyFlag=8,Mi.MATERIAL_MiscDirtyFlag=16,Mi.MATERIAL_PrePassDirtyFlag=32,Mi.MATERIAL_AllDirtyFlag=63,Mi.MATERIAL_TriangleFillMode=0,Mi.MATERIAL_WireFrameFillMode=1,Mi.MATERIAL_PointFillMode=2,Mi.MATERIAL_PointListDrawMode=3,Mi.MATERIAL_LineListDrawMode=4,Mi.MATERIAL_LineLoopDrawMode=5,Mi.MATERIAL_LineStripDrawMode=6,Mi.MATERIAL_TriangleStripDrawMode=7,Mi.MATERIAL_TriangleFanDrawMode=8,Mi.MATERIAL_ClockWiseSideOrientation=0,Mi.MATERIAL_CounterClockWiseSideOrientation=1,Mi.ACTION_NothingTrigger=0,Mi.ACTION_OnPickTrigger=1,Mi.ACTION_OnLeftPickTrigger=2,Mi.ACTION_OnRightPickTrigger=3,Mi.ACTION_OnCenterPickTrigger=4,Mi.ACTION_OnPickDownTrigger=5,Mi.ACTION_OnDoublePickTrigger=6,Mi.ACTION_OnPickUpTrigger=7,Mi.ACTION_OnPickOutTrigger=16,Mi.ACTION_OnLongPressTrigger=8,Mi.ACTION_OnPointerOverTrigger=9,Mi.ACTION_OnPointerOutTrigger=10,Mi.ACTION_OnEveryFrameTrigger=11,Mi.ACTION_OnIntersectionEnterTrigger=12,Mi.ACTION_OnIntersectionExitTrigger=13,Mi.ACTION_OnKeyDownTrigger=14,Mi.ACTION_OnKeyUpTrigger=15,Mi.PARTICLES_BILLBOARDMODE_Y=2,Mi.PARTICLES_BILLBOARDMODE_ALL=7,Mi.PARTICLES_BILLBOARDMODE_STRETCHED=8,Mi.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Mi.MESHES_CULLINGSTRATEGY_STANDARD=0,Mi.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Mi.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Mi.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Mi.SCENELOADER_NO_LOGGING=0,Mi.SCENELOADER_MINIMAL_LOGGING=1,Mi.SCENELOADER_SUMMARY_LOGGING=2,Mi.SCENELOADER_DETAILED_LOGGING=3,Mi.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Mi.PREPASS_POSITION_TEXTURE_TYPE=1,Mi.PREPASS_VELOCITY_TEXTURE_TYPE=2,Mi.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Mi.PREPASS_COLOR_TEXTURE_TYPE=4,Mi.PREPASS_DEPTH_TEXTURE_TYPE=5,Mi.PREPASS_NORMAL_TEXTURE_TYPE=6,Mi.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Mi.BUFFER_CREATIONFLAG_READ=1,Mi.BUFFER_CREATIONFLAG_WRITE=2,Mi.BUFFER_CREATIONFLAG_READWRITE=3,Mi.BUFFER_CREATIONFLAG_UNIFORM=4,Mi.BUFFER_CREATIONFLAG_VERTEX=8,Mi.BUFFER_CREATIONFLAG_INDEX=16,Mi.BUFFER_CREATIONFLAG_STORAGE=32,Mi.BUFFER_CREATIONFLAG_INDIRECT=64,Mi.RENDERPASS_MAIN=0,Mi.INPUT_ALT_KEY=18,Mi.INPUT_CTRL_KEY=17,Mi.INPUT_META_KEY1=91,Mi.INPUT_META_KEY2=92,Mi.INPUT_META_KEY3=93,Mi.INPUT_SHIFT_KEY=16,Mi.SNAPSHOTRENDERING_STANDARD=0,Mi.SNAPSHOTRENDERING_FAST=1,Mi.PERSPECTIVE_CAMERA=0,Mi.ORTHOGRAPHIC_CAMERA=1,Mi.FOVMODE_VERTICAL_FIXED=0,Mi.FOVMODE_HORIZONTAL_FIXED=1,Mi.RIG_MODE_NONE=0,Mi.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Mi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Mi.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Mi.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Mi.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Mi.RIG_MODE_VR=20,Mi.RIG_MODE_CUSTOM=22,Mi.MAX_SUPPORTED_UV_SETS=6,Mi.GL_ALPHA_EQUATION_ADD=32774,Mi.GL_ALPHA_EQUATION_MIN=32775,Mi.GL_ALPHA_EQUATION_MAX=32776,Mi.GL_ALPHA_EQUATION_SUBTRACT=32778,Mi.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Mi.GL_ALPHA_FUNCTION_SRC=768,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Mi.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Mi.GL_ALPHA_FUNCTION_DST_ALPHA=772,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Mi.GL_ALPHA_FUNCTION_DST_COLOR=774,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Mi.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Mi.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Mi.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Mi.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Mi.SnippetUrl="https://snippet.babylonjs.com",Mi.FOGMODE_NONE=0,Mi.FOGMODE_EXP=1,Mi.FOGMODE_EXP2=2,Mi.FOGMODE_LINEAR=3,Mi.BYTE=5120,Mi.UNSIGNED_BYTE=5121,Mi.SHORT=5122,Mi.UNSIGNED_SHORT=5123,Mi.INT=5124,Mi.UNSIGNED_INT=5125,Mi.FLOAT=5126,Mi.PositionKind="position",Mi.NormalKind="normal",Mi.TangentKind="tangent",Mi.UVKind="uv",Mi.UV2Kind="uv2",Mi.UV3Kind="uv3",Mi.UV4Kind="uv4",Mi.UV5Kind="uv5",Mi.UV6Kind="uv6",Mi.ColorKind="color",Mi.ColorInstanceKind="instanceColor",Mi.MatricesIndicesKind="matricesIndices",Mi.MatricesWeightsKind="matricesWeights",Mi.MatricesIndicesExtraKind="matricesIndicesExtra",Mi.MatricesWeightsExtraKind="matricesWeightsExtra";class bi{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach(((e,t)=>this.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function Si(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class yi{constructor(){this._dirty=!0,this._tempColor=new N(0,0,0,0),this._globalCurve=new N(0,0,0,0),this._highlightsCurve=new N(0,0,0,0),this._midtonesCurve=new N(0,0,0,0),this._shadowsCurve=new N(0,0,0,0),this._positiveCurve=new N(0,0,0,0),this._negativeCurve=new N(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",r="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(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=yi._Clamp(e,0,360),t=yi._Clamp(t,-100,100),i=yi._Clamp(i,-100,100),s=yi._Clamp(s,-100,100),t=yi._ApplyColorGradingSliderNonlinear(t),t*=.5,s=yi._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),yi._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.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 r=yi._Clamp(e,0,360);const n=yi._Clamp(t/100,0,1),a=yi._Clamp(i/100,0,1);if(0===n)s.r=a,s.g=a,s.b=a;else{r/=60;const e=Math.floor(r),t=r-e,i=a*(1-n),o=a*(1-n*t),h=a*(1-n*(1-t));switch(e){case 0:s.r=a,s.g=h,s.b=i;break;case 1:s.r=o,s.g=a,s.b=i;break;case 2:s.r=i,s.g=a,s.b=h;break;case 3:s.r=i,s.g=o,s.b=a;break;case 4:s.r=h,s.g=i,s.b=a;break;default:s.r=a,s.g=i,s.b=o}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return he.Clone((()=>new yi),this)}serialize(){return he.Serialize(this)}static Parse(e){return he.Parse((()=>new yi),e,null,null)}}yi.PrepareUniforms=Si,z([q()],yi.prototype,"_globalHue",void 0),z([q()],yi.prototype,"_globalDensity",void 0),z([q()],yi.prototype,"_globalSaturation",void 0),z([q()],yi.prototype,"_globalExposure",void 0),z([q()],yi.prototype,"_highlightsHue",void 0),z([q()],yi.prototype,"_highlightsDensity",void 0),z([q()],yi.prototype,"_highlightsSaturation",void 0),z([q()],yi.prototype,"_highlightsExposure",void 0),z([q()],yi.prototype,"_midtonesHue",void 0),z([q()],yi.prototype,"_midtonesDensity",void 0),z([q()],yi.prototype,"_midtonesSaturation",void 0),z([q()],yi.prototype,"_midtonesExposure",void 0),he._ColorCurvesParser=yi.Parse;class Ii{constructor(){this.colorCurves=new yi,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Ii.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new N(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Ii.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new se.cP}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)return 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,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Ii._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case Ii.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Ii.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,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&&yi.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),a=n*r;const o=Math.sqrt(a*n);a=(0,We.zF)(a,o,this.vignetteStretch),n=(0,We.zF)(n,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return he.Clone((()=>new Ii),this)}serialize(){return he.Serialize(this)}static Parse(e){const t=he.Parse((()=>new Ii),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}var Ri,Ci,Pi,Di,Oi,Fi,wi,Li;Ii.TONEMAPPING_STANDARD=0,Ii.TONEMAPPING_ACES=1,Ii.TONEMAPPING_KHR_PBR_NEUTRAL=2,Ii.PrepareUniforms=function(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Si(e),t.DITHER&&e.push("ditherIntensity")},Ii.PrepareSamplers=function(e,t){t.COLORGRADING&&e.push("txColorTransform")},Ii._VIGNETTEMODE_MULTIPLY=0,Ii._VIGNETTEMODE_OPAQUE=1,z([K(7,undefined)],Ii.prototype,"colorCurves",void 0),z([q()],Ii.prototype,"_colorCurvesEnabled",void 0),z([j("colorGradingTexture")],Ii.prototype,"_colorGradingTexture",void 0),z([q()],Ii.prototype,"_colorGradingEnabled",void 0),z([q()],Ii.prototype,"_colorGradingWithGreenDepth",void 0),z([q()],Ii.prototype,"_colorGradingBGR",void 0),z([q()],Ii.prototype,"_exposure",void 0),z([q()],Ii.prototype,"_toneMappingEnabled",void 0),z([q()],Ii.prototype,"_toneMappingType",void 0),z([q()],Ii.prototype,"_contrast",void 0),z([q()],Ii.prototype,"vignetteStretch",void 0),z([q()],Ii.prototype,"vignetteCenterX",void 0),z([q()],Ii.prototype,"vignetteCenterY",void 0),z([q()],Ii.prototype,"vignetteWeight",void 0),z([te()],Ii.prototype,"vignetteColor",void 0),z([q()],Ii.prototype,"vignetteCameraFov",void 0),z([q()],Ii.prototype,"_vignetteBlendMode",void 0),z([q()],Ii.prototype,"_vignetteEnabled",void 0),z([q()],Ii.prototype,"_ditheringEnabled",void 0),z([q()],Ii.prototype,"_ditheringIntensity",void 0),z([q()],Ii.prototype,"_skipFinalColorClamp",void 0),z([q()],Ii.prototype,"_applyByPostProcess",void 0),z([q()],Ii.prototype,"_isEnabled",void 0),he._ImageProcessingConfigurationParser=Ii.Parse,d("BABYLON.ImageProcessingConfiguration",Ii);class Ni{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(G.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=R.Vector3[0],n=R.Vector3[1],a=R.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(G.NormalKind);let t=s?M.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=s?M.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=s?M.FromArrayToRef(e,3*s[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),o=o.scale(this.bv),h=h.scale(1-this.bu-this.bv),i=new M(t.x+o.x+h.x,t.y+o.y+h.y,t.z+o.z+h.z)}else{const e=this.pickedMesh.getVerticesData(G.PositionKind),t=s?M.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=s?M.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=s?M.FromArrayToRef(e,3*s[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),l=t.subtract(o),c=h.subtract(o);i=M.Cross(l,c)}const o=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(R.Matrix[0].copyFrom(i),i=R.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(R.Matrix[1]),i=R.Matrix[1]),M.TransformNormalToRef(t,i,t)};if(e&&o(this.pickedMesh,i),this.ray){const t=R.Vector3[0].copyFrom(i);e||o(this.pickedMesh,t),M.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=G.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=A.FromArray(i,2*t[3*this.faceId]),r=A.FromArray(i,2*t[3*this.faceId+1]),n=A.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new A(s.x+r.x+n.x,s.y+r.y+n.y)}}class Bi{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new Bi(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Bi(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Bi(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Bi(e,t.x,t.y,null,i,s)}}class Ui{}Ui.POINTERDOWN=1,Ui.POINTERUP=2,Ui.POINTERMOVE=4,Ui.POINTERWHEEL=8,Ui.POINTERPICK=16,Ui.POINTERTAP=32,Ui.POINTERDOUBLETAP=64;class ki{constructor(e,t){this.type=e,this.event=t}}class Vi extends ki{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new A(i,s)}}class Gi extends ki{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,s=null){super(e,t),this._pickInfo=i,this._inputManager=s}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class zi{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in zi.Triggers)if(Object.prototype.hasOwnProperty.call(zi.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in zi.Triggers)if(Object.prototype.hasOwnProperty.call(zi.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in zi.Triggers)if(Object.prototype.hasOwnProperty.call(zi.Triggers,t)&&parseInt(t)===e)return!0;return!1}}zi.Triggers={};class Wi{}Wi.KEYDOWN=1,Wi.KEYUP=2;class Xi{constructor(e,t){this.type=e,this.event=t}}class Hi extends Xi{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}}!function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(Ri||(Ri={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(Ci||(Ci={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(Pi||(Pi={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Di||(Di={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Oi||(Oi={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(Fi||(Fi={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(wi||(wi={})),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(Li||(Li={}));class Ki{}Ki.DOM_DELTA_PIXEL=0,Ki.DOM_DELTA_LINE=1,Ki.DOM_DELTA_PAGE=2;class Yi{static CreateDeviceEvent(e,t,i,s,r,n,a){switch(e){case Ri.Keyboard:return this._CreateKeyboardEvent(i,s,r,n);case Ri.Mouse:if(i===Ci.MouseWheelX||i===Ci.MouseWheelY||i===Ci.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,r,n);case Ri.Touch:return this._CreatePointerEvent(e,t,i,s,r,n,a);default:throw`Unable to generate event for device ${Ri[e]}`}}static _CreatePointerEvent(e,t,i,s,r,n,a){const o=this._CreateMouseEvent(e,t,i,s,r,n);e===Ri.Mouse?(o.deviceType=Ri.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=Ri.Touch,o.pointerId=a??t,o.pointerType="touch");let h=0;return h+=r.pollInput(e,t,Ci.LeftClick),h+=2*r.pollInput(e,t,Ci.RightClick),h+=4*r.pollInput(e,t,Ci.MiddleClick),o.buttons=h,i===Ci.Move?o.type="pointermove":i>=Ci.LeftClick&&i<=Ci.RightClick&&(o.type=1===s?"pointerdown":"pointerup",o.button=i-2),o}static _CreateWheelEvent(e,t,i,s,r,n){const a=this._CreateMouseEvent(e,t,i,s,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=Ki.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case Ci.MouseWheelX:a.deltaX=s;break;case Ci.MouseWheelY:a.deltaY=s;break;case Ci.MouseWheelZ:a.deltaZ=s}return a}static _CreateMouseEvent(e,t,i,s,r,n){const a=this._CreateEvent(n),o=r.pollInput(e,t,Ci.Horizontal),h=r.pollInput(e,t,Ci.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,Pi.DeltaHorizontal),a.movementY=r.pollInput(e,t,Pi.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=o,a.clientY=h,a.x=o,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=Ri.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(Ri.Keyboard),s=i&&1===t.pollInput(Ri.Keyboard,0,18),r=i&&1===t.pollInput(Ri.Keyboard,0,17),n=i&&(1===t.pollInput(Ri.Keyboard,0,91)||1===t.pollInput(Ri.Keyboard,0,92)||1===t.pollInput(Ri.Keyboard,0,93)),a=i&&1===t.pollInput(Ri.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class qi{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=Yi.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Ri.Mouse||e===Ri.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const ji=Object.keys(Ci).length/2;class Zi{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Xe.IsSafari(),this._usingMacOS=(0,de.XD)()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=(0,de.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=(0,de.XD)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Xe.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 ${Ri[e]}`;e>=Ri.DualShock&&e<=Ri.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${Ri[e]} in slot ${t}`;return i===Ci.Move&&Xe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ri.Keyboard,0,255));const t=this._inputs[Ri.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(Ri.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Ri.Keyboard,0,255));const t=this._inputs[Ri.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=Yi.CreateDeviceEvent(Ri.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Ri.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Ri.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[Ri.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===Ri.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ri.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void Xe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=Ci.Move,s[Ci.Horizontal]=e.clientX,s[Ci.Vertical]=e.clientY,t===Ri.Touch&&0===s[Ci.LeftClick]&&(s[Ci.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===Ri.Mouse?0:e.pointerId;if(t===Ri.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Xe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===Ri.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[Ci.Horizontal],n=s[Ci.Vertical];if(t===Ri.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[Ci.Horizontal]=e.clientX,s[Ci.Vertical]=e.clientY,s[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,i,a),r===e.clientX&&n===e.clientY||(a.inputIndex=Ci.Move,this._onInputChanged(t,i,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===Ri.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Ri.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[Ci.Horizontal],n=s[Ci.Vertical];s[Ci.Horizontal]=e.clientX,s[Ci.Vertical]=e.clientY,s[e.button+2]=0;const a=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(a.inputIndex=Ci.Move,this._onInputChanged(t,i,a)),a.inputIndex=e.button+2,t===Ri.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,a),t===Ri.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[Ri.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Ci.LeftClick;t<=Ci.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Yi.CreateDeviceEvent(Ri.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ri.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[Ri.Touch][t][Ci.LeftClick]=0;const i=Yi.CreateDeviceEvent(Ri.Touch,t,Ci.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(Ri.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Ri.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"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(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(Ri.Mouse)){const e=this._inputs[Ri.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Ci.LeftClick;t<=Ci.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Yi.CreateDeviceEvent(Ri.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Ri.Mouse,0,i)}}if(this.isDeviceAvailable(Ri.Touch)){const e=this._inputs[Ri.Touch];for(let t=0;t{const t=Ri.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,ji));const i=this._inputs[t][0];if(i){i[Ci.MouseWheelX]=e.deltaX||0,i[Ci.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[Ci.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[Ci.MouseWheelX]&&(s.inputIndex=Ci.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[Ci.MouseWheelY]&&(s.inputIndex=Ci.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[Ci.MouseWheelZ]&&(s.inputIndex=Ci.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},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}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(Ri.Mouse)){const e=this._inputs[Ri.Mouse][0];e[Ci.MouseWheelX]=0,e[Ci.MouseWheelY]=0,e[Ci.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Ri.DualSense:Ri.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Ri.Xbox:-1!==e.indexOf("057e")?Ri.Switch:Ri.Generic}_getPointerType(e){let t=Ri.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Ri.Touch),t}}class Qi{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new se.cP,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class $i{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(Ri).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new Qi(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new qi(i,s,r):this._deviceInputSystem=new Zi(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Ji{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(Ri).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new $i(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new se.cP((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new se.cP,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){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Ri.Keyboard:case Ri.Mouse:this._firstDevice[e]=0;break;case Ri.Touch:case Ri.DualSense:case Ri.DualShock:case Ri.Xbox:case Ri.Switch:case Ri.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=Ci.MouseWheelX&&t.inputIndex<=Ci.MouseWheelZ?Ui.POINTERWHEEL:Ui.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(a=new Gi(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new Gi(n,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,y.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new Vi(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=Ci.Move,this._checkPrePointerObservable(e,i,Ui.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,Ui.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,Bi.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,Bi.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,Bi.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,Bi.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>ts.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,Bi.CreateNew(e.pickedMesh,t)))}),ts.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=Ui.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new Gi(r,t,e),this._setRayOnPointerInfo(e,t)):s=new Gi(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=Ci.Move;const r=new es;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,Ui.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=Ui.POINTERPICK,r=new Gi(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,Bi.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,Bi.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,Bi.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,Bi.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new Gi(Ui.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,Ui.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,Ui.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=Ui.POINTERTAP:i.doubleClick&&(r=Ui.POINTERDOUBLETAP),r){const i=new Gi(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Ji(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>ts.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=Ui.POINTERTAP,s=new Gi(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new es;this._currentPickResult=null;let n=null,a=e.hasSpecificMask(Ui.POINTERPICK)||t.hasSpecificMask(Ui.POINTERPICK)||e.hasSpecificMask(Ui.POINTERTAP)||t.hasSpecificMask(Ui.POINTERTAP)||e.hasSpecificMask(Ui.POINTERDOUBLETAP)||t.hasSpecificMask(Ui.POINTERDOUBLETAP);!a&&zi&&(n=this._initActionManager(n,r),n&&(a=n.hasPickTriggers));let o=!1;if(a){const a=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let h=!ts.ExclusiveDoubleClickMode;if(h||(h=!e.hasSpecificMask(Ui.POINTERDOUBLETAP)&&!t.hasSpecificMask(Ui.POINTERDOUBLETAP),h&&!zi.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=!n.hasSpecificTrigger(6)))),h)(Date.now()-this._previousStartingPointerTime>ts.DoubleClickDelay||a!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),o=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,a,r,s),ts.DoubleClickDelay)};this._delayedClicks[a]=e}let l=e.hasSpecificMask(Ui.POINTERDOUBLETAP)||t.hasSpecificMask(Ui.POINTERDOUBLETAP);!l&&zi.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=n.hasSpecificTrigger(6))),l&&(a===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>ts.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>ts.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=Ci.MouseWheelX&&e.inputIndex<=Ci.MouseWheelZ?Ui.POINTERWHEEL:Ui.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new Ni,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,ts.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new Ni:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,Ui.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(Ui.POINTERTAP)&&this._checkPrePointerObservable(null,e,Ui.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(Ui.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,Ui.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||0!=(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(zi&&zi.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=Wi.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new Hi(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Xi(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,Bi.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Wi.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new Hi(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new Xi(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,Bi.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===Ri.Mouse?s.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===Ci.LeftClick||r.inputIndex===Ci.MiddleClick||r.inputIndex===Ci.RightClick||r.inputIndex===Ci.BrowserBack||r.inputIndex===Ci.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===Ci.Move?this._onPointerMove(r):r.inputIndex!==Ci.MouseWheelX&&r.inputIndex!==Ci.MouseWheelY&&r.inputIndex!==Ci.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===Ri.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===Ci.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===Ci.Move&&this._onPointerMove(r)})):s.deviceType===Ri.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,Bi.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,Bi.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]}}ts.DragMovementThreshold=10,ts.LongPressDelay=500,ts.DoubleClickDelay=300,ts.ExclusiveDoubleClickMode=!1;var is,ss=i(296);class rs{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}rs._UniqueIdCounter=1;class ns{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(is||(is={}));class as extends mi{static DefaultMaterialFactory(e){throw(0,re.n)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,re.n)("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case is.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case is.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case is.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return ts.DragMovementThreshold}static set DragMovementThreshold(e){ts.DragMovementThreshold=e}static get LongPressDelay(){return ts.LongPressDelay}static set LongPressDelay(e){ts.LongPressDelay=e}static get DoubleClickDelay(){return ts.DoubleClickDelay}static set DoubleClickDelay(e){ts.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return ts.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){ts.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return R.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,R.Vector4[0].x,R.Vector4[0].y,R.Vector4[0].z):e.setVector4(t,R.Vector4[0])),R.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=l(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=as.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=as.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new ts(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new N(.2,.2,.3,1),this.ambientColor=new L(0,0,0),this.environmentIntensity=1,this._performancePriority=is.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new se.cP,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new se.cP,this._onDisposeObserver=null,this.onBeforeRenderObservable=new se.cP,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new se.cP,this.onAfterRenderCameraObservable=new se.cP,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new se.cP,this.onAfterAnimationsObservable=new se.cP,this.onBeforeDrawPhaseObservable=new se.cP,this.onAfterDrawPhaseObservable=new se.cP,this.onReadyObservable=new se.cP,this.onBeforeCameraRenderObservable=new se.cP,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new se.cP,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new se.cP,this.onAfterActiveMeshesEvaluationObservable=new se.cP,this.onBeforeParticlesRenderingObservable=new se.cP,this.onAfterParticlesRenderingObservable=new se.cP,this.onDataLoadedObservable=new se.cP,this.onNewCameraAddedObservable=new se.cP,this.onCameraRemovedObservable=new se.cP,this.onNewLightAddedObservable=new se.cP,this.onLightRemovedObservable=new se.cP,this.onNewGeometryAddedObservable=new se.cP,this.onGeometryRemovedObservable=new se.cP,this.onNewTransformNodeAddedObservable=new se.cP,this.onTransformNodeRemovedObservable=new se.cP,this.onNewMeshAddedObservable=new se.cP,this.onMeshRemovedObservable=new se.cP,this.onNewSkeletonAddedObservable=new se.cP,this.onSkeletonRemovedObservable=new se.cP,this.onNewMaterialAddedObservable=new se.cP,this.onNewMultiMaterialAddedObservable=new se.cP,this.onMaterialRemovedObservable=new se.cP,this.onMultiMaterialRemovedObservable=new se.cP,this.onNewTextureAddedObservable=new se.cP,this.onTextureRemovedObservable=new se.cP,this.onBeforeRenderTargetsRenderObservable=new se.cP,this.onAfterRenderTargetsRenderObservable=new se.cP,this.onBeforeStepObservable=new se.cP,this.onAfterStepObservable=new se.cP,this.onActiveCameraChanged=new se.cP,this.onActiveCamerasChanged=new se.cP,this.onBeforeRenderingGroupObservable=new se.cP,this.onAfterRenderingGroupObservable=new se.cP,this.onMeshImportedObservable=new se.cP,this.onAnimationFileImportedObservable=new se.cP,this._registeredForLateAnimationBindings=new at(256),this._pointerPickingConfiguration=new ns,this.onPrePointerObservable=new se.cP,this.onPointerObservable=new se.cP,this.onPreKeyboardObservable=new se.cP,this.onKeyboardObservable=new se.cP,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=as.FOGMODE_NONE,this.fogColor=new L(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new M(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new at(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new ss.A,this._activeIndices=new ss.A,this._activeParticles=new ss.A,this._activeBones=new ss.A,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 nt(256),this._processedMaterials=new nt(256),this._renderTargets=new at(256),this._materialsRenderTargets=new at(256),this._activeParticleSystems=new nt(256),this._activeSkeletons=new at(32),this._softwareSkinnedMeshes=new at(32),this._activeAnimatables=new Array,this._transformMatrix=y.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=gi.Create(),this._beforeClearStage=gi.Create(),this._beforeRenderTargetClearStage=gi.Create(),this._gatherRenderTargetsStage=gi.Create(),this._gatherActiveCameraRenderTargetsStage=gi.Create(),this._isReadyForMeshStage=gi.Create(),this._beforeEvaluateActiveMeshStage=gi.Create(),this._evaluateSubMeshStage=gi.Create(),this._preActiveMeshStage=gi.Create(),this._cameraDrawRenderTargetStage=gi.Create(),this._beforeCameraDrawStage=gi.Create(),this._beforeRenderTargetDrawStage=gi.Create(),this._beforeRenderingGroupDrawStage=gi.Create(),this._beforeRenderingMeshStage=gi.Create(),this._afterRenderingMeshStage=gi.Create(),this._afterRenderingGroupDrawStage=gi.Create(),this._afterCameraDrawStage=gi.Create(),this._afterCameraPostProcessStage=gi.Create(),this._afterRenderTargetDrawStage=gi.Create(),this._afterRenderTargetPostProcessStage=gi.Create(),this._afterRenderStage=gi.Create(),this._pointerMoveStage=gi.Create(),this._pointerDownStage=gi.Create(),this._pointerUpStage=gi.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||_.q.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(_.q._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new lt(this),rt&&(this.postProcessManager=new rt(this)),(0,de.BA)()&&this.attachControl(),this._createUbo(),Ii&&(this._imageProcessingConfiguration=new Ii),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 void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const a=s.material||this.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else a.hasRenderTargetTextures&&null!=a.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(a)&&(this._processedMaterials.push(a),this._materialsRenderTargets.concatWithNoDuplicate(a.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}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){void 0!==t?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);-1!==i&&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),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=_e.j.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?ri.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ri.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new qe(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return rs.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._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-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._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(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,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-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||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){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&0!=(t.layerMask&this.activeCamera.layerMask)&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Xe.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(Bi.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(as.MinDeltaTime,Math.min(this._engine.getDeltaTime(),as.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.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 t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){k.V.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),_.q._LastCreatedScene===this&&(this._engine.scenes.length>0?_.q._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:_.q._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;M.CheckExtends(r,t,i),M.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw(0,re.n)("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,a=!1){throw(0,re.n)("Ray")}createPickingRayInCameraSpace(e,t,i){throw(0,re.n)("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw(0,re.n)("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const a=(0,re.n)("Ray",!0);return a&&k.V.Warn(a),new Ni}pickWithBoundingInfo(e,t,i,s,r){const n=(0,re.n)("Ray",!0);return n&&k.V.Warn(n),new Ni}pickWithRay(e,t,i,s){throw(0,re.n)("Ray")}multiPick(e,t,i,s,r){throw(0,re.n)("Ray")}multiPickWithRay(e,t,i){throw(0,re.n)("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(void 0===t)return e;const s=[];for(const r in e){const n=e[r];ae&&ae.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_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,r,n,a){const o=Fe(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_loadFileAsync(e,t,i,s,r){return new Promise(((n,a)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{a(t)}),r)}))}_requestFile(e,t,i,s,r,n,a){const o=we(e,t,i,s?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_requestFileAsync(e,t,i,s,r){return new Promise(((n,a)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{a(e)}),r)}))}_readFile(e,t,i,s,r){const n=Oe(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw(0,re.n)("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)}}as.FOGMODE_NONE=0,as.FOGMODE_EXP=1,as.FOGMODE_EXP2=2,as.FOGMODE_LINEAR=3,as.MinDeltaTime=1,as.MaxDeltaTime=1e3,d("BABYLON.Scene",as);class os{static AdditionalUV1Kind="additionalUv1";static AdditionalUV2Kind="additionalUv2";static AdditionalUV3Kind="additionalUv3";static AdditionalUV4Kind="additionalUv4";static MatricesSdefCKind="matricesSdefC";static MatricesSdefR0Kind="matricesSdefR0";static MatricesSdefR1Kind="matricesSdefR1";static EdgeScaleKind="edgeScale"}const hs="\n#ifndef SDEFDECLARATION\n#define SDEFDECLARATION\n#if NUM_BONE_INFLUENCERS>0 && defined(SDEF)\nattribute vec3 matricesSdefC;attribute vec3 matricesSdefR0;attribute vec3 matricesSdefR1;vec4 rotationMatrixToQuaternion(mat3 matrix) {float trace=matrix[0][0]+matrix[1][1]+matrix[2][2];float s;float sqrtParam;if (trace>0.0) {sqrtParam=trace+1.0;} else if (matrix[0][0]>matrix[1][1] && matrix[0][0]>matrix[2][2]) {sqrtParam=1.0+matrix[0][0]-matrix[1][1]-matrix[2][2];} else if (matrix[1][1]>matrix[2][2]) {sqrtParam=1.0+matrix[1][1]-matrix[0][0]-matrix[2][2];} else {sqrtParam=1.0+matrix[2][2]-matrix[0][0]-matrix[1][1];}\nfloat sqrtValue=sqrt(sqrtParam);if (trace>0.0) {s=0.5/sqrtValue;return vec4(\n(matrix[1][2]-matrix[2][1])*s,\n(matrix[2][0]-matrix[0][2])*s,\n(matrix[0][1]-matrix[1][0])*s,\n0.25/s\n);} else if (matrix[0][0]>matrix[1][1] && matrix[0][0]>matrix[2][2]) {s=2.0*sqrtValue;return vec4(\n0.25*s,\n(matrix[0][1]+matrix[1][0])/s,\n(matrix[2][0]+matrix[0][2])/s,\n(matrix[1][2]-matrix[2][1])/s\n);} else if (matrix[1][1]>matrix[2][2]) {s=2.0*sqrtValue;return vec4(\n(matrix[0][1]+matrix[1][0])/s,\n0.25*s,\n(matrix[1][2]+matrix[2][1])/s,\n(matrix[2][0]-matrix[0][2])/s\n);} else {s=2.0*sqrtValue;return vec4(\n(matrix[2][0]+matrix[0][2])/s,\n(matrix[1][2]+matrix[2][1])/s,\n0.25*s,\n(matrix[0][1]-matrix[1][0])/s\n);}}\nmat3 quaternionToRotationMatrix(vec4 q) {float xx=q.x*q.x;float yy=q.y*q.y;float zz=q.z*q.z;float xy=q.x*q.y;float zw=q.z*q.w;float zx=q.z*q.x;float yw=q.y*q.w;float yz=q.y*q.z;float xw=q.x*q.w;return mat3(\n1.0-2.0*(yy+zz),2.0*(xy+zw),2.0*(zx-yw),\n2.0*(xy-zw),1.0-2.0*(zz+xx),2.0*(yz+xw),\n2.0*(zx+yw),2.0*(yz-xw),1.0-2.0*(yy+xx)\n);}\nvec4 slerp(vec4 q0,vec4 q1,float t) {float cosTheta=dot(q0,q1);q1=mix(-q1,q1,step(0.0,cosTheta));cosTheta=abs(cosTheta);if (cosTheta>0.999999) {return normalize(mix(q0,q1,t));}\nfloat theta=acos(cosTheta);float sinTheta=sin(theta);float w0=sin((1.0-t)*theta)/sinTheta;float w1=sin(t*theta)/sinTheta;return q0*w0+q1*w1;}\n#endif\n#endif\n",ls="\n#ifndef SDEFVERTEX\n#define SDEFVERTEX\n#if !defined(BAKED_VERTEX_ANIMATION_TEXTURE) && defined(SDEF)\n#if NUM_BONE_INFLUENCERS>0\n{float weight0=matricesWeights[0];float weight1=matricesWeights[1];\n#ifdef BONETEXTURE\nmat4 transformMatrix0=readMatrixFromRawSampler(boneSampler,matricesIndices[0]);mat4 transformMatrix1=readMatrixFromRawSampler(boneSampler,matricesIndices[1]);\n#else\nmat4 transformMatrix0=mBones[int(matricesIndices[0])];mat4 transformMatrix1=mBones[int(matricesIndices[1])];\n#endif\nmat3 slerpedRotationMatrix=quaternionToRotationMatrix(slerp(\nrotationMatrixToQuaternion(mat3(transformMatrix0)),\nrotationMatrixToQuaternion(mat3(transformMatrix1)),\nweight1\n));mat4 sdefInflunce=mat4(\nvec4(1.0,0.0,0.0,0.0),\nvec4(0.0,1.0,0.0,0.0),\nvec4(0.0,0.0,1.0,0.0),\nvec4(-matricesSdefC,1.0)\n);mat4 rotationMatrix=mat4(\nvec4(slerpedRotationMatrix[0],0.0),\nvec4(slerpedRotationMatrix[1],0.0),\nvec4(slerpedRotationMatrix[2],0.0),\nvec4(0.0,0.0,0.0,1.0)\n);sdefInflunce=rotationMatrix*sdefInflunce;vec3 positionOffset =\nvec3(transformMatrix0*vec4(matricesSdefR0,1))*weight0 +\nvec3(transformMatrix1*vec4(matricesSdefR1,1))*weight1;sdefInflunce[3]+=vec4(positionOffset,0.0);float useLinearDeform=step(0.0,-abs(matricesSdefR0.x));influence=mat4(\nmix(sdefInflunce[0],influence[0],useLinearDeform),\nmix(sdefInflunce[1],influence[1],useLinearDeform),\nmix(sdefInflunce[2],influence[2],useLinearDeform),\nmix(sdefInflunce[3],influence[3],useLinearDeform)\n);}\n#endif\n#endif\n#endif\n";class cs{static OverrideEngineCreateEffect(e){const t=e.createEffect.bind(e);e.createEffect=function(e,i,s,r,n,a,o,h,l,c=yt.w.GLSL){let d;if(d=i.attributes?i:{attributes:i,uniformsNames:s,uniformBuffersNames:[],samplers:r??[],defines:n??"",fallbacks:a??null,onCompiled:o??null,onError:h??null,indexParameters:l??null,shaderLanguage:c},(d.shaderLanguage===yt.w.GLSL||void 0===d.shaderLanguage)&&(d.uniformsNames.includes("mBones")||d.samplers.includes("boneSampler"))&&-1===d.defines.indexOf("#define SDEF")){d.attributes.push(os.MatricesSdefCKind),d.attributes.push(os.MatricesSdefR0Kind),d.attributes.push(os.MatricesSdefR1Kind),d.defines+="\n#define SDEF";const e=d.processCodeAfterIncludes;d.processCodeAfterIncludes=e?function(t,i){return i=e(t,i),cs.ProcessSdefCode(t,i)}:cs.ProcessSdefCode}return t(e,d,this)}}static ProcessSdefCode(e,t){if("vertex"!==e)return t;const i="#define CUSTOM_VERTEX_DEFINITIONS";if(t.includes(i))t=t.replace(i,`${i}\n${hs}`);else{const e="void main() {";t=t.replace(e,`${hs}\nvoid main() {`)}const s=new RegExp("finalWorld=finalWorld\\*influence;","g");return t.replace(s,`${ls}\nfinalWorld=finalWorld*influence;`)}}_t.M.RegisterShader("mmdOutline","\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n","\nattribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform vec2 viewport;uniform mat3 view;uniform mat4 viewProjection;\n#ifdef WORLDPOS_REQUIRED\nuniform mat4 inverseViewProjection;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec3 viewNormal=view*(mat3(finalWorld)*normalUpdated);vec4 projectedPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vec2 screenNormal=normalize(vec2(viewNormal));projectedPosition.xy+=screenNormal/(viewport*0.25/*0.5 */)*offset*projectedPosition.w;gl_Position=projectedPosition;\n#ifdef WORLDPOS_REQUIRED\nvec4 worldPos=inverseViewProjection*projectedPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n"),as.prototype.getMmdOutlineRenderer=function(){return this._mmdOutlineRenderer||(this._mmdOutlineRenderer=new ds(this)),this._mmdOutlineRenderer};class ds{name="MmdOutline";scene;_engine;_passIdForDrawWrapper;constructor(e){this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=this._engine.createRenderPassId("Mmd Outline Renderer")}register(){this.scene._afterRenderingMeshStage.registerStep(pi.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){this._engine.releaseRenderPassId(this._passIdForDrawWrapper)}static _ViewMatrix=new Float32Array(9);static _InverseViewProjectionMatrix=new y;render(e,t,i){i=i??this._passIdForDrawWrapper;const s=this.scene,r=s.getEngine(),n=r.getCaps().instancedArrays&&(null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id]||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,n,i))return;const a=e.getMesh(),o=a._internalAbstractMeshDataInfo._actAsRegularMesh?a:null,h=e.getRenderingMesh(),l=o||h,c=e.getMaterial();if(!c||!s.activeCamera)return;const d=e._getDrawWrapper(i),u=pt.GetEffect(d);r.enableEffect(d),c.useLogarithmicDepth&&u.setFloat("logarithmicDepthConstant",2/(Math.log(s.activeCamera.maxZ+1)/Math.LN2)),u.setFloat("offset",c.outlineWidth),u.setColor4("color",c.outlineColor,c.outlineAlpha);const f=r.getRenderHeight(),_=r.getRenderWidth();u.setFloat2("viewport",_,f);const p=ds._ViewMatrix;{const e=s.getViewMatrix().m;p[0]=e[0],p[1]=e[1],p[2]=e[2],p[3]=e[4],p[4]=e[5],p[5]=e[6],p[6]=e[8],p[7]=e[9],p[8]=e[10]}if(u.setMatrix3x3("view",p),u.setMatrix("viewProjection",s.getTransformMatrix()),u.setMatrix("world",l.getWorldMatrix()),Kt(l,u),h.morphTargetManager&&h.morphTargetManager.isUsingTextureForTargets&&h.morphTargetManager._bind(u),Gt(h,u),n||h._bind(e,u,c.fillMode),c&&c.needAlphaTesting()){const e=c.getAlphaTestTexture();e&&(u.setTexture("diffuseSampler",e),u.setMatrix("diffuseMatrix",e.getTextureMatrix()))}Ot(u,c,s),u.defines.includes("WORLDPOS_REQUIRED")&&u.setMatrix("inverseViewProjection",s.getTransformMatrix().invertToRef(ds._InverseViewProjectionMatrix)),h._processRendering(l,e,u,c.fillMode,t,n,((e,t)=>{u.setMatrix("world",t)}))}isReady(e,t,i){i=i??this._passIdForDrawWrapper;const s=[],r=[G.PositionKind,G.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;const o=n.getScene();a.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(G.UVKind)&&(r.push(G.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(G.UV2Kind)&&(r.push(G.UV2Kind),s.push("#define UV2"))),a.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),Dt(a,o,s);let h=!1;for(let e=0;e4&&(r.push(G.MatricesIndicesExtraKind),r.push(G.MatricesWeightsExtraKind)),n.isVerticesDataPresent(os.MatricesSdefCKind)&&(r.push(os.MatricesSdefCKind),r.push(os.MatricesSdefR0Kind),r.push(os.MatricesSdefR1Kind),s.push("#define SDEF"));const e=n.skeleton;s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),n.numBoneInfluencers>0&&l.addCPUSkinningFallback(0,n),e.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(e.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");const c=n.morphTargetManager;let d=0;c&&(d=c.numMaxInfluencers||c.numInfluencers,d>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+d),c.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Ut(r,n,d))),t&&(s.push("#define INSTANCES"),Vt(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const u=e._getDrawWrapper(i,!0),f=u.defines,_=s.join("\n");if(f!==_){const e=["world","mBones","viewport","view","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","boneTextureWidth","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"],t=["diffuseSampler","boneSampler","morphTargets"];Pt(e),h&&e.push("inverseViewProjection"),u.setEffect(this.scene.getEngine().createEffect("mmdOutline",{attributes:r,uniformsNames:e,samplers:t,defines:_,indexParameters:{maxSimultaneousMorphTargets:d},processCodeAfterIncludes:cs.ProcessSdefCode},this.scene.getEngine()),_)}return u.effect.isReady()}_afterRenderingMesh(e,t,i){const s=t.getMaterial();if(null!==s&&s.renderOutline){const e=this._engine,s=e.getDepthWrite(),r=e.getAlphaMode();e.setDepthWrite(!0),e.setAlphaMode(Mi.ALPHA_COMBINE,!0),e.setState(!0,void 0,void 0,void 0,!!this.scene._mirroredCameraPosition),this.render(t,i,this._passIdForDrawWrapper),e.setAlphaMode(r,!0),e.setDepthWrite(s)}}}class us{static get ForceFullSceneLoadingForIncremental(){return us._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){us._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return us._ShowLoadingScreen}static set ShowLoadingScreen(e){us._ShowLoadingScreen=e}static get loggingLevel(){return us._LoggingLevel}static set loggingLevel(e){us._LoggingLevel=e}static get CleanBoneMatrixWeights(){return us._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){us._CleanBoneMatrixWeights=e}}var fs,_s,ps,gs,ms;us._ForceFullSceneLoadingForIncremental=!1,us._ShowLoadingScreen=!0,us._CleanBoneMatrixWeights=!1,us._LoggingLevel=0,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(fs||(fs={}));class Ts{static get ForceFullSceneLoadingForIncremental(){return us.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){us.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return us.ShowLoadingScreen}static set ShowLoadingScreen(e){us.ShowLoadingScreen=e}static get loggingLevel(){return us.loggingLevel}static set loggingLevel(e){us.loggingLevel=e}static get CleanBoneMatrixWeights(){return us.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){us.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Ts._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return Ts._RegisteredPlugins[e]||(k.V.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),Ts.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Ts._RegisteredPlugins){const i=Ts._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ts._RegisteredPlugins[t]}return Ts.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Ts._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,a,o){const h=Ts._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const l=a?Ts._GetPluginForExtension(a):h?Ts._GetPluginForDirectLoad(e.url):Ts._GetPluginForFilename(e.url);if(e.rawData&&!l.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==l.plugin.createPlugin?l.plugin.createPlugin():l.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(Ts.OnPluginActivatedObservable.notifyObservers(c),h&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!Ne(e.url))){if(c.directLoad){const e=c.directLoad(t,h);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,h);return c}const d=l.isBinary,u=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let f=null,_=!1;const p=c.onDisposeObservable;p&&p.add((()=>{_=!0,f&&(f.abort(),f=null),n()}));const g=()=>{if(_)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";f=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,u,s,d,i,o):t._loadFile(e.file||e.url,u,s,!0,d,i)},m=t.getEngine();let T=m.enableOfflineSupport;if(T){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}T=!i}return T&&Ai.N.OfflineProviderFactory?t.offlineProvider=Ai.N.OfflineProviderFactory(e.url,g,m.disableManifestCheck):g(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=ze(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return Xe.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=Xe.GetFilename(e),e=Xe.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Ts._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Ts._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Ts._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Ts._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=_.q.LastCreatedScene,r=null,n=null,a=null,o=null,h=""){if(!s)return k.V.Error("No scene available to import mesh to"),null;const l=Ts._GetFileInfo(t,i);if(!l)return null;const c={};s.addPendingData(c);const d=()=>{s.removePendingData(c)},u=(e,t)=>{const i=Ts._FormatErrorMessage(l,e,t);a?a(s,i,new xe(i,Te,t)):k.V.Error(i),d()},f=n?e=>{try{n(e)}catch(e){u("Error in onProgress callback: "+e,e)}}:void 0,p=(e,t,i,n,a,o,h,d)=>{if(s.importedMeshesFiles.push(l.url),r)try{r(e,t,i,n,a,o,h,d)}catch(e){u("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return Ts._LoadData(l,s,((t,i,r)=>{if(t.rewriteRootURL&&(l.rootUrl=t.rewriteRootURL(l.rootUrl,r)),t.importMesh){const r=[],n=[],a=[];if(!t.importMesh(e,s,i,l.rootUrl,r,n,a,u))return;s.loadingPluginName=t.name,p(r,n,a,[],[],[],[],[])}else t.importMeshAsync(e,s,i,l.rootUrl,f,l.name).then((e=>{s.loadingPluginName=t.name,p(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{u(e.message,e)}))}),f,u,d,o,h)}static ImportMeshAsync(e,t,i="",s=_.q.LastCreatedScene,r=null,n=null,a=""){return new Promise(((o,h)=>{Ts.ImportMesh(e,t,i,s,((e,t,i,s,r,n,a,h)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:a,spriteManagers:h})}),r,((e,t,i)=>{h(i||new Error(t))}),n,a)}))}static Load(e,t="",i=_.q.LastCreatedEngine,s=null,r=null,n=null,a=null,o=""){return i?Ts.Append(e,t,new as(i),s,r,n,a,o):(Xe.Error("No engine available"),null)}static LoadAsync(e,t="",i=_.q.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((a,o)=>{Ts.Load(e,t,i,(e=>{a(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r,n)}))}static Append(e,t="",i=_.q.LastCreatedScene,s=null,r=null,n=null,a=null,o=""){if(!i)return k.V.Error("No scene available to append to"),null;const h=Ts._GetFileInfo(e,t);if(!h)return null;const l={};i.addPendingData(l);const c=()=>{i.removePendingData(l)};Ts.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const d=(e,t)=>{const s=Ts._FormatErrorMessage(h,e,t);n?n(i,s,new xe(s,Te,t)):k.V.Error(s),c()},u=r?e=>{try{r(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=()=>{if(s)try{s(i)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(l)};return Ts._LoadData(h,i,((e,t)=>{if(e.load){if(!e.load(i,t,h.rootUrl,d))return;i.loadingPluginName=e.name,f()}else e.loadAsync(i,t,h.rootUrl,u,h.name).then((()=>{i.loadingPluginName=e.name,f()})).catch((e=>{d(e.message,e)}))}),u,d,c,a,o)}static AppendAsync(e,t="",i=_.q.LastCreatedScene,s=null,r=null,n=""){return new Promise(((a,o)=>{Ts.Append(e,t,i,(e=>{a(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=_.q.LastCreatedScene,s=null,r=null,n=null,a=null,o=""){if(!i)return k.V.Error("No scene available to load asset container to"),null;const h=Ts._GetFileInfo(e,t);if(!h)return null;const l={};i.addPendingData(l);const c=()=>{i.removePendingData(l)},d=(e,t)=>{const s=Ts._FormatErrorMessage(h,e,t);n?n(i,s,new xe(s,Te,t)):k.V.Error(s),c()},u=r?e=>{try{r(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=e=>{if(s)try{s(e)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(l)};return Ts._LoadData(h,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,h.rootUrl,d);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,f(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,h.rootUrl,u,h.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,f(t)})).catch((e=>{d(e.message,e)})):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),u,d,c,a,o)}static LoadAssetContainerAsync(e,t="",i=_.q.LastCreatedScene,s=null,r=null){return new Promise(((n,a)=>{Ts.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=_.q.LastCreatedScene,s=!0,r=fs.Clean,n=null,a=null,o=null,h=null,l=null){if(!i)return void k.V.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case fs.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case fs.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case fs.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case fs.NoSync:break;default:return void k.V.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)}),o,h,l)}static ImportAnimationsAsync(e,t="",i=_.q.LastCreatedScene,s=!0,r=fs.Clean,n=null,a=null,o=null,h=null,l=null){return new Promise(((a,h)=>{Ts.ImportAnimations(e,t,i,s,r,n,(e=>{a(e)}),o,((e,t,i)=>{h(i||new Error(t))}),l)}))}}Ts.NO_LOGGING=0,Ts.MINIMAL_LOGGING=1,Ts.SUMMARY_LOGGING=2,Ts.DETAILED_LOGGING=3,Ts.OnPluginActivatedObservable=new se.cP,Ts._RegisteredPlugins={},Ts._ShowingLoadingScreen=!1;class xs{log(e){console.log(e)}warn(e){console.warn(e)}error(e){console.error(e)}}class Es{isDeviceLittleEndian;_dataView;_decoder;_offset;constructor(e){this.isDeviceLittleEndian=this._getIsDeviceLittleEndian(),this._dataView=new DataView(e),this._decoder=null,this._offset=0}get offset(){return this._offset}set offset(e){this._offset=e}_getIsDeviceLittleEndian(){const e=new Int16Array([256]);return 1===new Int8Array(e.buffer)[1]}swap16Array(e){for(let t=0;t>8&255}}swap32Array(e){for(let t=0;t>8&65280|i>>24&255}}getUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}getInt8(){const e=this._dataView.getInt8(this._offset);return this._offset+=1,e}getUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);e.set(t),this._offset+=e.byteLength}getUint16(){const e=this._dataView.getUint16(this._offset,!0);return this._offset+=2,e}getUint16Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap16Array(e)}getInt16(){const e=this._dataView.getInt16(this._offset,!0);return this._offset+=2,e}getUint32(){const e=this._dataView.getUint32(this._offset,!0);return this._offset+=4,e}getUint32Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap32Array(e)}getInt32(){const e=this._dataView.getInt32(this._offset,!0);return this._offset+=4,e}getInt32Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap32Array(e)}getFloat32(){const e=this._dataView.getFloat32(this._offset,!0);return this._offset+=4,e}getFloat32Array(e){const t=new Uint8Array(this._dataView.buffer,this._offset,e.byteLength);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t),this._offset+=e.byteLength,this.isDeviceLittleEndian||this.swap32Array(e)}getFloat32Tuple(e){const t=new Array(e);for(let i=0;i0&&t.warn(`There are ${i.bytesAvailable} bytes left after parsing`),{header:s,vertices:r,indices:n,textures:u,materials:f,bones:p,morphs:l,displayFrames:c,rigidBodies:_,joints:g,softBodies:[]}}static _ParseHeader(e){if(e.bytesAvailable<7)throw new Error("is not pmd file");const t=e.getSignatureString(3);if("Pmd"!==t)throw new Error("is not pmd file");const i=e.getFloat32(),s=e.getDecoderString(20,!0),r=e.getDecoderString(256,!0);return{signature:t,version:i,encoding:ps.Header.Encoding.ShiftJis,additionalVec4Count:0,vertexIndexSize:2,textureIndexSize:4,materialIndexSize:4,boneIndexSize:2,morphIndexSize:2,rigidBodyIndexSize:4,modelName:s,englishModelName:"",comment:r,englishComment:""}}static async _ParseVerticesAsync(e){const t=e.getUint32(),i=[];let s=performance.now();for(let r=0;rsetTimeout(e,0))),s=performance.now())}return i}static _ParseIndices(e){const t=e.getUint32(),i=new Uint16Array(t);return e.getUint16Array(i),i}static _ParseMaterials(e){const t=e.getUint32(),i=[];for(let s=0;sl[e+1][1]){c=!1;break}if(!c){l.sort(((e,t)=>e[1]-t[1]));const e=new Array(l.length);for(let t=1;tl[t][0]||void 0!==e[t-1])&&(i=!1),i||(e[t]=a[l[t-1][0]])}const t=new Map;for(let i=0;i{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function Ms(e,t,i,s,r){const n=()=>{let a;const o=e=>{e.done?i(e.value):void 0===a?a=!0:n()};do{a=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,o,s),void 0===a&&(a=!1)}while(a)};n()}function bs(e,t){let i;return Ms(e,As,(e=>i=e),(e=>{throw e}),t),i}class Ss{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class ys{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let a=i;a!Array.isArray(e)&&!Array.isArray(t)))],ys,"extractMinAndMaxIndexed",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],ys,"extractMinAndMax",null);class Rs{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new pt(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,a,o=!0){return new Rs(e,t,i,s,r,n,a,o)}constructor(e,t,i,s,r,n,a,o=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,h&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,o&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&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(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(G.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=function(e,t,i,s,r=null){const n=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new M(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return ys.extractMinAndMaxIndexed(e,t,i,s,n,a),r&&(n.x-=n.x*r.x+r.y,n.y-=n.y*r.x+r.y,n.z-=n.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:n,maximum:a}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new si(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)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}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 t=this.indexStart;to&&(o=t)}return new Rs(e,a,o-a+1,t,i,s,r,n)}}class Cs{}class Ps{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>bs(e(...t),undefined)),this.uniqueId=Ps._UniqueIDGenerator,Ps._UniqueIDGenerator++}set(e,t){switch(e.length||k.V.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case G.PositionKind:this.positions=e;break;case G.NormalKind:this.normals=e;break;case G.TangentKind:this.tangents=e;break;case G.UVKind:this.uvs=e;break;case G.UV2Kind:this.uvs2=e;break;case G.UV3Kind:this.uvs3=e;break;case G.UV4Kind:this.uvs4=e;break;case G.UV5Kind:this.uvs5=e;break;case G.UV6Kind:this.uvs6=e;break;case G.ColorKind:this.colors=e;break;case G.MatricesIndicesKind:this.matricesIndices=e;break;case G.MatricesWeightsKind:this.matricesWeights=e;break;case G.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case G.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}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(G.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(G.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(G.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(G.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(G.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(G.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(G.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(G.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(G.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(G.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(G.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(G.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(G.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(G.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 t=e;t.subMeshes=[];for(const e of this.materialInfos)new Rs(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(G.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(G.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(G.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(G.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(G.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(G.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(G.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(G.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(G.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(G.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(G.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(G.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(G.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(G.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=R.Vector3[0],n=R.Vector3[1];for(let a=i;a({vertexData:e}))):[{vertexData:e}];return bs(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,a=!1){this._validate();let o=t.map((e=>e.vertexData)),h=this;if(a)for(const e of o)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of o)if(e)if(a)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let a=null;const l=[];for(const t of this.splitBasedOnMaterialID())l.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())l.push({vertexData:t,transform:e.transform});l.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of l){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{const e=new Cs;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),a=e}s+=t.indices.length,r+=t.positions.length/3}const c=l.splice(0,1)[0];h=c.vertexData,e=c.transform,o=l.map((e=>e.vertexData)),t=l,this.materialInfos=n}const l=o.reduce(((e,t)=>e+(t.indices?.length??0)),h.indices?.length??0);let c=r||o.some((e=>e.indices===h.indices))?h.indices?.slice():h.indices;if(l>0){let r=c?.length??0;if(c||(c=new Array(l)),c.length!==l){if(Array.isArray(c))c.length=l;else{const e=i||c instanceof Uint32Array?new Uint32Array(l):new Uint16Array(l);e.set(c),c=e}e&&e.determinant()<0&&Ps._FlipFaces(c,0,r)}let n=h.positions?h.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),h.normals&&(this.normals=Ps._MergeElement(G.NormalKind,h.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),h.tangents&&(this.tangents=Ps._MergeElement(G.TangentKind,h.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),h.uvs&&(this.uvs=Ps._MergeElement(G.UVKind,h.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),h.uvs2&&(this.uvs2=Ps._MergeElement(G.UV2Kind,h.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),h.uvs3&&(this.uvs3=Ps._MergeElement(G.UV3Kind,h.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),h.uvs4&&(this.uvs4=Ps._MergeElement(G.UV4Kind,h.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),h.uvs5&&(this.uvs5=Ps._MergeElement(G.UV5Kind,h.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),h.uvs6&&(this.uvs6=Ps._MergeElement(G.UV6Kind,h.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),h.colors&&(this.colors=Ps._MergeElement(G.ColorKind,h.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==h.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=h.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),h.matricesIndices&&(this.matricesIndices=Ps._MergeElement(G.MatricesIndicesKind,h.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),h.matricesWeights&&(this.matricesWeights=Ps._MergeElement(G.MatricesWeightsKind,h.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),h.matricesIndicesExtra&&(this.matricesIndicesExtra=Ps._MergeElement(G.MatricesIndicesExtraKind,h.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),h.matricesWeightsExtra&&(this.matricesWeightsExtra=Ps._MergeElement(G.MatricesWeightsExtraKind,h.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),a=e===G.PositionKind?Ps._TransformVector3Coordinates:e===G.NormalKind?Ps._TransformVector3Normals:e===G.TangentKind?Ps._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&a(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&a(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=G.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(G.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(G.NormalKind,this.normals),this.tangents&&i(G.TangentKind,this.tangents),this.uvs&&i(G.UVKind,this.uvs),this.uvs2&&i(G.UV2Kind,this.uvs2),this.uvs3&&i(G.UV3Kind,this.uvs3),this.uvs4&&i(G.UV4Kind,this.uvs4),this.uvs5&&i(G.UV5Kind,this.uvs5),this.uvs6&&i(G.UV6Kind,this.uvs6),this.colors&&i(G.ColorKind,this.colors),this.matricesIndices&&i(G.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(G.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(G.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(G.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Ps.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 Ps._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Ps._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Ps;if(e.isVerticesDataPresent(G.PositionKind)&&(s.positions=e.getVerticesData(G.PositionKind,t,i)),e.isVerticesDataPresent(G.NormalKind)&&(s.normals=e.getVerticesData(G.NormalKind,t,i)),e.isVerticesDataPresent(G.TangentKind)&&(s.tangents=e.getVerticesData(G.TangentKind,t,i)),e.isVerticesDataPresent(G.UVKind)&&(s.uvs=e.getVerticesData(G.UVKind,t,i)),e.isVerticesDataPresent(G.UV2Kind)&&(s.uvs2=e.getVerticesData(G.UV2Kind,t,i)),e.isVerticesDataPresent(G.UV3Kind)&&(s.uvs3=e.getVerticesData(G.UV3Kind,t,i)),e.isVerticesDataPresent(G.UV4Kind)&&(s.uvs4=e.getVerticesData(G.UV4Kind,t,i)),e.isVerticesDataPresent(G.UV5Kind)&&(s.uvs5=e.getVerticesData(G.UV5Kind,t,i)),e.isVerticesDataPresent(G.UV6Kind)&&(s.uvs6=e.getVerticesData(G.UV6Kind,t,i)),e.isVerticesDataPresent(G.ColorKind)){const r=e.geometry||e,n=r.getVertexBuffer(G.ColorKind),a=r.getVerticesData(G.ColorKind,t,i);if(3===n.getSize()){const e=new Float32Array(4*a.length/3);for(let t=0,i=0;t!Array.isArray(e)))],Ps,"_TransformVector3Coordinates",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],Ps,"_TransformVector3Normals",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],Ps,"_TransformVector4Normals",null),z([ie.filter(((...[e])=>!Array.isArray(e)))],Ps,"_FlipFaces",null);class Ds{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 Ds(Ds.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||_.q.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._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 r=new G(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}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 r=this._meshes,n=r.length;if(s===G.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new M(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}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);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&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(G.PositionKind)))return;this._extend=Is(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===G.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&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 e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Ps;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(G.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(G.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(G.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(it.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(G.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(G.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(G.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(G.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(G.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(G.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(G.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Ds._CleanMatricesWeights(e,t),t.setVerticesData(G.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(G.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(G.MatricesIndicesKind),n=t.getVerticesData(G.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,l=a.length;for(let e=0;eh-1)&&(l=h-1),t>i){const i=1/t;for(let t=0;t<4;t++)a[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else l>=4?(o[e+l-4]=1-t,n[e+l-4]=s):(a[e+l]=1-t,r[e+l]=s)}t.setVerticesData(G.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(G.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new Ds(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,ae&&ae.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new si(M.FromArray(e.boundingBoxMinimum),M.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(G.UVKind),e.hasUVs2&&s._delayInfo.push(G.UV2Kind),e.hasUVs3&&s._delayInfo.push(G.UV3Kind),e.hasUVs4&&s._delayInfo.push(G.UV4Kind),e.hasUVs5&&s._delayInfo.push(G.UV5Kind),e.hasUVs6&&s._delayInfo.push(G.UV6Kind),e.hasColors&&s._delayInfo.push(G.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(G.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(G.MatricesWeightsKind),s._delayLoadingFunction=Ps.ImportVertexData):Ps.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(gs||(gs={}));class Os{}Os.X=new M(1,0,0),Os.Y=new M(0,1,0),Os.Z=new M(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(ms||(ms={}));const Fs=y.Compose(M.One(),S.FromEulerAngles(0,Math.PI,0),M.Zero());class ws extends ce{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=0!=(this._billboardMode&ws.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==ws.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 M(0,0,1),this._up=new M(0,1,0),this._right=new M(1,0,0),this._position=M.Zero(),this._rotation=M.Zero(),this._rotationQuaternion=null,this._scaling=M.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=ws.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=y.Zero(),this._usePivotMatrix=!1,this._absolutePosition=M.Zero(),this._absoluteScaling=M.Zero(),this._absoluteRotationQuaternion=S.Identity(),this._pivotMatrix=y.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new se.cP,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return M.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return M.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return M.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=y.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==ws.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=y.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 e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||S.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(void 0===e.x){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 e=R.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),M.TransformCoordinatesFromFloatsToRef(t,i,s,e,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=M.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=R.Matrix[0];return this._localMatrix.invertToRef(e),M.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=M.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=gs.LOCAL){const n=ws._LookAtVectorCache,a=r===gs.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,i,s),r===gs.WORLD&&this.parent)if(this.rotationQuaternion){const e=R.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=R.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=R.Quaternion[0];S.FromEulerVectorToRef(this.rotation,e);const t=R.Matrix[0];e.toRotationMatrix(t);const i=R.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=M.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return M.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?S.RotationYawPitchRollToRef(r+t,a+i,s,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=gs.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==gs.WORLD){const t=R.Matrix[0];i.invertToRef(t),e=M.TransformCoordinates(e,t)}return this.setPivotMatrix(y.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=M.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=M.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),M.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=R.Quaternion[0],r=R.Vector3[0],n=R.Vector3[1],a=R.Matrix[1];y.IdentityToRef(a);const o=R.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=ws._TmpRotation,S.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),y.ComposeToRef(this.scaling,h,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(a),o.multiplyToRef(a,o)),o.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(y.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&&(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,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==gs.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=R.Matrix[0];i.invertToRef(s),e=M.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=S.RotationAxisToRef(e,t,ws._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=S.RotationAxisToRef(e,t,ws._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=S.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=R.Vector3[0],r=R.Vector3[1],n=R.Vector3[2],a=R.Quaternion[0],o=R.Matrix[0],h=R.Matrix[1],l=R.Matrix[2],c=R.Matrix[3];return e.subtractToRef(this.position,s),y.TranslationToRef(s.x,s.y,s.z,o),y.TranslationToRef(-s.x,-s.y,-s.z,h),y.RotationAxisToRef(t,i,l),h.multiplyToRef(l,c),c.multiplyToRef(o,c),c.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==gs.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=R.Quaternion[1],S.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=R.Quaternion[0];return S.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==ws.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=ws._TmpScaling;let a,o=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new M(e.m[12],e.m[13],e.m[14]);o=ws._TmpTranslation,o.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,a=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(S.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(a=ws._TmpRotation,S.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a)),this._usePivotMatrix){const e=R.Matrix[1];y.ScalingToRef(n.x,n.y,n.z,e);const t=R.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,R.Matrix[4]),R.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else y.ComposeToRef(n,a,o,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),R.Matrix[7])}else R.Matrix[7].copyFrom(r.getWorldMatrix());const e=R.Vector3[5],t=R.Vector3[6],i=R.Quaternion[0];R.Matrix[7].decompose(t,i,e),y.ScalingToRef(t.x,t.y,t.z,R.Matrix[7]),R.Matrix[7].setTranslation(e),ws.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(R.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),R.Matrix[6]),R.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=R.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),R.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&R.Matrix[1].multiplyToRef(Fs,R.Matrix[1]),R.Matrix[1].setTranslationFromFloats(0,0,0),R.Matrix[1].invertToRef(R.Matrix[0]),(this.billboardMode&ws.BILLBOARDMODE_ALL)!==ws.BILLBOARDMODE_ALL){R.Matrix[0].decompose(void 0,R.Quaternion[0],void 0);const e=R.Vector3[1];R.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&ws.BILLBOARDMODE_X)!==ws.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&ws.BILLBOARDMODE_Y)!==ws.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&ws.BILLBOARDMODE_Z)!==ws.BILLBOARDMODE_Z&&(e.z=0),y.RotationYawPitchRollToRef(e.y,e.x,e.z,R.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(R.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(R.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=R.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(R.Matrix[1]);const s=R.Vector3[1];M.TransformCoordinatesToRef(i,R.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),a=-Math.atan2(s.y,n);if(S.RotationYawPitchRollToRef(r,a,0,R.Quaternion[0]),(this.billboardMode&ws.BILLBOARDMODE_ALL)!==ws.BILLBOARDMODE_ALL){const e=R.Vector3[1];R.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&ws.BILLBOARDMODE_X)!==ws.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&ws.BILLBOARDMODE_Y)!==ws.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&ws.BILLBOARDMODE_Z)!==ws.BILLBOARDMODE_Z&&(e.z=0),y.RotationYawPitchRollToRef(e.y,e.x,e.z,R.Matrix[0])}else y.FromQuaternionToRef(R.Quaternion[0],R.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(R.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(R.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=y.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew ws(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew ws(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(y.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(y.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof ws)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);if(0===o)return this;const h=1/o;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}ws.BILLBOARDMODE_NONE=0,ws.BILLBOARDMODE_X=1,ws.BILLBOARDMODE_Y=2,ws.BILLBOARDMODE_Z=4,ws.BILLBOARDMODE_ALL=7,ws.BILLBOARDMODE_USE_POSITION=128,ws.BillboardUseParentOrientation=!1,ws._TmpRotation=S.Zero(),ws._TmpScaling=M.Zero(),ws._TmpTranslation=M.Zero(),ws._LookAtVectorCache=new M(0,0,0),ws._RotationAxisCache=new S,z([J("position")],ws.prototype,"_position",void 0),z([J("rotation")],ws.prototype,"_rotation",void 0),z([K(10,"rotationQuaternion")],ws.prototype,"_rotationQuaternion",void 0),z([J("scaling")],ws.prototype,"_scaling",void 0),z([q("billboardMode")],ws.prototype,"_billboardMode",void 0),z([q()],ws.prototype,"scalingDeterminant",void 0),z([q("infiniteDistance")],ws.prototype,"_infiniteDistance",void 0),z([q()],ws.prototype,"ignoreNonUniformScaling",void 0),z([q()],ws.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Ls{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new M(0,0,0),this._diffPositionForCollisions=new M(0,0,0),this._collisionResponse=!0}}class Ns{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=M.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class Bs{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Ns,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 Ls,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Us extends ws{static get BILLBOARDMODE_NONE(){return ws.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return ws.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return ws.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return ws.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return ws.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return ws.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)}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,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Bs,this._waitingMaterialId=null,this.cullingStrategy=Us.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new se.cP,this.onCollisionPositionChangeObservable=new se.cP,this.onMaterialChangedObservable=new se.cP,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=L.Red(),this.outlineWidth=.02,this.overlayColor=L.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 M(.5,1,.5),this.ellipsoidOffset=new M(0,0,0),this.edgesWidth=1,this.edgesColor=new N(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new se.cP,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ai.N.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new qe(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case is.Aggressive:this.doNotSyncBoundingInfo=!0;case is.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_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: "+("InstancedMesh"!==this.getClassName()?"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!==ws.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._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(-1===i){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);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new si(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(G.MatricesIndicesKind)&&this.isVerticesDataPresent(G.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===ws.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 y;(this.rotationQuaternion?this.rotationQuaternion:S.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=M.Zero(),n=this.definedFacingForward?-1:1;return M.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,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 M(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=Is(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new si(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(G.MatricesIndicesExtraKind):null,a=r?this.getVerticesData(G.MatricesWeightsExtraKind):null,o=this.skeleton.getTransformMatrices(this),h=R.Vector3[0],l=R.Matrix[0],c=R.Matrix[1];let d=0;for(let u=0;u0&&(y.FromFloat32ArrayToRefScaled(o,Math.floor(16*e[d+f]),_,c),l.addToSelf(c));if(r)for(f=0;f<4;f++)_=a[d+f],_>0&&(y.FromFloat32ArrayToRefScaled(o,Math.floor(16*n[d+f]),_,c),l.addToSelf(c));s===G.NormalKind?M.TransformNormalFromFloatsToRef(i[u],i[u+1],i[u+2],l,h):M.TransformCoordinatesFromFloatsToRef(i[u],i[u+1],i[u+2],l,h),h.toArray(i,u),s===G.PositionKind&&this._positions&&this._positions[u/3].copyFrom(h)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,G.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,G.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(G.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.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 t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=R.Matrix[0],i=R.Matrix[1];return y.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const a=new Ni,o=this.getClassName(),h="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,l=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(n||e.intersectsSphere(l.boundingSphere,h)&&e.intersectsBox(l.boundingBox,h)))return a;if(s)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:M.Distance(e.origin,l.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let c=null;const d=this._scene.getIntersectingSubMeshCandidates(this,e),u=d.length;let f=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const a=r.intersects(e,this._positions,this.getIndices(),t,i);if(a&&(t||!c||a.distancee!==this&&e.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 t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:M.Zero()}e.depthSortedFacets=[];for(let t=0;ta?r.maximum.x-r.minimum.x:a,e.bbSize.y=r.maximum.y-r.minimum.y>a?r.maximum.y-r.minimum.y:a,e.bbSize.z=r.maximum.z-r.minimum.z>a?r.maximum.z-r.minimum.z:a;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),M.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Ps.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||a<0||a>r.subDiv.max||o<0||o>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const a=this.getWorldMatrix(),o=R.Matrix[5];a.invertToRef(o);const h=R.Vector3[8];M.TransformCoordinatesFromFloatsToRef(e,t,i,o,h);const l=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,s,r,n);return s&&M.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,a,s),l}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let a=null,o=0,h=0,l=0,c=0,d=0,u=0,f=0,_=0;const p=this.getFacetLocalPositions(),g=this.getFacetLocalNormals(),m=this.getFacetsAtLocalCoordinates(e,t,i);if(!m)return null;let T,x,E,v=Number.MAX_VALUE,A=v;for(let M=0;M=0||r&&!n&&c<=0)&&(c=x.x*E.x+x.y*E.y+x.z*E.z,d=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),u=e+x.x*d,f=t+x.y*d,_=i+x.z*d,o=u-e,h=f-t,l=_-i,A=o*o+h*h+l*l,Ae.emitter===this))}}Us.OCCLUSION_TYPE_NONE=0,Us.OCCLUSION_TYPE_OPTIMISTIC=1,Us.OCCLUSION_TYPE_STRICT=2,Us.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Us.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Us.CULLINGSTRATEGY_STANDARD=0,Us.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Us.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Us.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,d("BABYLON.AbstractMesh",Us);class ks{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){he.Clone((()=>e),this)}serialize(){return he.Serialize(this)}parse(e,t,i){he.Parse((()=>this),e,t,i)}}var Vs,Gs,zs;z([q()],ks.prototype,"func",null),z([q()],ks.prototype,"funcRef",null),z([q()],ks.prototype,"funcMask",null),z([q()],ks.prototype,"opStencilFail",null),z([q()],ks.prototype,"opDepthFail",null),z([q()],ks.prototype,"opStencilDepthPass",null),z([q()],ks.prototype,"mask",null),z([q()],ks.prototype,"enabled",null),(zs=Vs||(Vs={}))[zs.Created=1]="Created",zs[zs.Disposed=2]="Disposed",zs[zs.GetDefineNames=4]="GetDefineNames",zs[zs.PrepareUniformBuffer=8]="PrepareUniformBuffer",zs[zs.IsReadyForSubMesh=16]="IsReadyForSubMesh",zs[zs.PrepareDefines=32]="PrepareDefines",zs[zs.BindForSubMesh=64]="BindForSubMesh",zs[zs.PrepareEffect=128]="PrepareEffect",zs[zs.GetAnimatables=256]="GetAnimatables",zs[zs.GetActiveTextures=512]="GetActiveTextures",zs[zs.HasTexture=1024]="HasTexture",zs[zs.FillRenderTargetTextures=2048]="FillRenderTargetTextures",zs[zs.HasRenderTargetTextures=4096]="HasRenderTargetTextures",zs[zs.HardBindForSubMesh=8192]="HardBindForSubMesh";class Ws{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,1!==t&&1!==e||this.markAsDirty(Ws.MiscDirtyFlag+Ws.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Ws.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Ws.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new se.cP),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new se.cP),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new se.cP),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Ws.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(Ws.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Ws.WireFrameFillMode:case Ws.LineListDrawMode:case Ws.LineLoopDrawMode:case Ws.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Ws.WireFrameFillMode:Ws.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Ws.PointFillMode:case Ws.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Ws.PointFillMode:Ws.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Ws.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&k.V.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new se.cP,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new ks,this._useUBO=!1,this._fillMode=Ws.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||_.q.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Xe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new pt(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Ws.ClockWiseSideOrientation:this.sideOrientation=Ws.CounterClockWiseSideOrientation,this._uniformBuffer=new qe(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Ws.OnEventObservable.notifyObservers(this,Vs.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Ws.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Ws.MATERIAL_OPAQUE||this._transparencyMode===Ws.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(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 t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(Ws.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===Ws.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Vs.PrepareUniformBuffer,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,zt(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&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(Vs.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Vs.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Vs.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Ws._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new et(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new Rs(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);r.clipPlane&&(n.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Ws._DirtyCallbackArray.length=0,e&Ws.TextureDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._TextureDirtyCallBack),e&Ws.LightDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._LightsDirtyCallBack),e&Ws.FresnelDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._FresnelDirtyCallBack),e&Ws.AttributesDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._AttributeDirtyCallBack),e&Ws.MiscDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._MiscDirtyCallBack),e&Ws.PrePassDirtyFlag&&Ws._DirtyCallbackArray.push(Ws._PrePassDirtyCallBack),Ws._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Ws._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.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 t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Ws._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Ws._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Ws._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Ws._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Ws._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Ws._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Ws._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Ws._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Ws._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Ws._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==is.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Vs.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=he.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){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return k.V.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=Xe.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let a=t.pluginManager?.getPlugin(n.name);if(!a){const e=Xe.Instantiate("BABYLON."+r);e&&(a=new e(t))}a?.parse(n,i,s)}}}Ws.TriangleFillMode=0,Ws.WireFrameFillMode=1,Ws.PointFillMode=2,Ws.PointListDrawMode=3,Ws.LineListDrawMode=4,Ws.LineLoopDrawMode=5,Ws.LineStripDrawMode=6,Ws.TriangleStripDrawMode=7,Ws.TriangleFanDrawMode=8,Ws.ClockWiseSideOrientation=0,Ws.CounterClockWiseSideOrientation=1,Ws.TextureDirtyFlag=1,Ws.LightDirtyFlag=2,Ws.FresnelDirtyFlag=4,Ws.AttributesDirtyFlag=8,Ws.MiscDirtyFlag=16,Ws.PrePassDirtyFlag=32,Ws.AllDirtyFlag=63,Ws.MATERIAL_OPAQUE=0,Ws.MATERIAL_ALPHATEST=1,Ws.MATERIAL_ALPHABLEND=2,Ws.MATERIAL_ALPHATESTANDBLEND=3,Ws.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Ws.MATERIAL_NORMALBLENDMETHOD_RNM=1,Ws.OnEventObservable=new se.cP,Ws._AllDirtyCallBack=e=>e.markAllAsDirty(),Ws._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Ws._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Ws._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Ws._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Ws._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Ws._LightsDirtyCallBack=e=>e.markAsLightDirty(),Ws._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Ws._FresnelAndMiscDirtyCallBack=e=>{Ws._FresnelDirtyCallBack(e),Ws._MiscDirtyCallBack(e)},Ws._TextureAndMiscDirtyCallBack=e=>{Ws._TextureDirtyCallBack(e),Ws._MiscDirtyCallBack(e)},Ws._DirtyCallbackArray=[],Ws._RunDirtyCallBacks=e=>{for(const t of Ws._DirtyCallbackArray)t(e)},z([q()],Ws.prototype,"id",void 0),z([q()],Ws.prototype,"uniqueId",void 0),z([q()],Ws.prototype,"name",void 0),z([q()],Ws.prototype,"metadata",void 0),z([q()],Ws.prototype,"checkReadyOnEveryCall",void 0),z([q()],Ws.prototype,"checkReadyOnlyOnce",void 0),z([q()],Ws.prototype,"state",void 0),z([q("alpha")],Ws.prototype,"_alpha",void 0),z([q("backFaceCulling")],Ws.prototype,"_backFaceCulling",void 0),z([q("cullBackFaces")],Ws.prototype,"_cullBackFaces",void 0),z([q()],Ws.prototype,"sideOrientation",void 0),z([q("alphaMode")],Ws.prototype,"_alphaMode",void 0),z([q()],Ws.prototype,"_needDepthPrePass",void 0),z([q()],Ws.prototype,"disableDepthWrite",void 0),z([q()],Ws.prototype,"disableColorWrite",void 0),z([q()],Ws.prototype,"forceDepthWrite",void 0),z([q()],Ws.prototype,"depthFunction",void 0),z([q()],Ws.prototype,"separateCullingPass",void 0),z([q("fogEnabled")],Ws.prototype,"_fogEnabled",void 0),z([q()],Ws.prototype,"pointSize",void 0),z([q()],Ws.prototype,"zOffset",void 0),z([q()],Ws.prototype,"zOffsetUnits",void 0),z([q()],Ws.prototype,"pointsCloud",null),z([q()],Ws.prototype,"fillMode",null),z([q()],Ws.prototype,"useLogarithmicDepth",null),z([q()],Ws.prototype,"transparencyMode",null);class Xs extends Ws{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=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);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){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new Xs(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,ae&&ae.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}d("BABYLON.MultiMaterial",Xs);class Hs{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class Ks{constructor(){this.visibleInstances={},this.batchCache=new Ys,this.batchCacheReplacementModeInFrozenMode=new Ys,this.instancesBufferSize=2048}}class Ys{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class qs{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class js{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 Zs extends Us{static _GetDefaultSideOrientation(e){return e||Zs.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(G.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(G.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new se.cP),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new se.cP),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new se.cP),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new se.cP),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new se.cP),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new js,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new Ks,this._thinInstanceDataStorage=new qs,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Zs.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),fe.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,ae&&ae.HasTags(s)&&ae.AddTagsTo(this,ae.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new se.cP(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||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 e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.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 k.V.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Hs(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;ia*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const a=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new Rs(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)Rs.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new Ps;s.set(t,e);const r=this.getScene();new Ds(Ds.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Ds.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(G.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(G.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(G.NormalKind);if(!t)return this;Ps.ComputeNormals(i,e,t),this.updateVerticesData(G.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(Ds.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new Ds(Ds.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Ps;t.indices=e;const s=this.getScene();new Ds(Ds.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case Ws.PointFillMode:n=null;break;case Ws.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Ws.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==Ws.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ws.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),a=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&a&&(n.visibleInstances[e]=t[a])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],a=n?n.length:0,o=this._instanceDataStorage,h=o.instancesBufferSize;let l=o.instancesBuffer,c=o.instancesPreviousBuffer;const d=16*(a+1)*4;for(;o.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const a=s.getEngine();let o=0,h=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(o=s.activeCamera.maxZ,h=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const l=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||l.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,d=this._instanceDataStorage,u=e.getMaterial();if(!u)return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this;if(d.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===u){if(u._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!u._storeEffectOnSubMeshes&&!u._getDrawWrapper()._wasPreviouslyReady)return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this}else{if(u._storeEffectOnSubMeshes){if(!u.isReadyForSubMesh(this,e,c))return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this}else if(!u.isReady(this,c))return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=u}let f;t&&a.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),f=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const _=f?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,_);if(!f||!_)return h&&(h.maxZ=o,s.updateTransformMatrix(!0)),this;const p=i||this;let g;if(d.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)g=d.sideOrientation;else{const e=p._getWorldMatrixDeterminant();g=this.overrideMaterialSideOrientation,null==g&&(g=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(g=g===Ws.ClockWiseSideOrientation?Ws.CounterClockWiseSideOrientation:Ws.ClockWiseSideOrientation),d.sideOrientation=g}const m=this._internalMeshDataInfo._effectiveMaterial._preBind(f,g);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&a.setDepthWrite(!0);const T=this._internalMeshDataInfo._effectiveMaterial,x=T.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,_,x,!1);const E=p.getWorldMatrix();T._storeEffectOnSubMeshes?T.bindForSubMesh(E,this,e):T.bind(E,this),!T.backFaceCulling&&T.separateCullingPass&&(a.setState(!0,T.zOffset,!1,!m,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._processRendering(this,e,_,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),a.setState(!0,T.zOffset,!1,m,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,_,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,_);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),h&&(h.maxZ=o,s.updateTransformMatrix(!0)),s.performancePriority!==is.Aggressive||d.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(G.MatricesWeightsKind)&&(this.isVerticesDataPresent(G.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(G.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&d++,c+=n,i=n}if(h[d]++,d>n&&(n=d),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&a++}}const l=this.skeleton.bones.length,c=this.getVerticesData(G.MatricesIndicesKind),d=this.getVerticesData(G.MatricesIndicesExtraKind);let u=0;for(let e=0;e=l||i<0)&&u++}return{skinned:!0,valid:0===r&&0===a&&0===u,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+a+"\nWeightCounts = ["+h+"]\nNumber of bones = "+l+"\nBad Bone Indices = "+u}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Xe.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(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(G.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(G.PositionKind);const s=M.Zero();let r;for(r=0;r{const o=e.width,h=e.height,l=this.getEngine().createCanvas(o,h).getContext("2d");l.drawImage(e,0,0);const c=l.getImageData(0,0,o,h).data;this.applyDisplacementMapFromBuffer(c,o,h,t,i,r,n,a),s&&s(this)}),o||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,a,o=!1){if(!this.isVerticesDataPresent(G.PositionKind)||!this.isVerticesDataPresent(G.NormalKind)||!this.isVerticesDataPresent(G.UVKind))return k.V.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(G.PositionKind,!0,!0),l=this.getVerticesData(G.NormalKind),c=this.getVerticesData(G.UVKind);let d=M.Zero();const u=M.Zero(),f=A.Zero();n=n||A.Zero(),a=a||new A(1,1);for(let o=0;o{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,h=o?this.getVerticesData(G.MatricesIndicesExtraKind):null,l=o?this.getVerticesData(G.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),d=M.Zero(),u=new y,f=new y;let _,p=0;for(let e=0;e0&&(y.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[p+_]),g,f),u.addToSelf(f));if(o)for(_=0;_<4;_++)g=l[p+_],g>0&&(y.FromFloat32ArrayToRefScaled(c,Math.floor(16*h[p+_]),g,f),u.addToSelf(f));M.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],u,d),d.toArray(s,e),t&&(M.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],u,d),d.toArray(r,e)),u.reset()}return this.updateVerticesData(G.PositionKind,s),t&&this.updateVerticesData(G.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:M.Zero(),max:M.Zero()}}static Center(e){const t=e instanceof Array?Zs.MinMax(e):e;return M.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return bs(Zs._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return a=Zs._MergeMeshesCoroutine(e,t,i,s,r,n,!0),o=function(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{As(i,s,r)}),0)):As(i,s,r)}}(),new Promise(((e,t)=>{Ms(a,o,e,t,h)}));var a,o,h}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,a){if(0===(e=e.filter(Boolean)).length)return null;let o;if(!i){let t=0;for(o=0;o=65536)return k.V.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const h=new Array,l=new Array,c=new Array,d=e[0].overrideMaterialSideOrientation;for(o=0;o{const t=e.computeWorldMatrix(!0);return{vertexData:Ps.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:_,transform:p}=f(u);a&&(yield);const g=new Array(e.length-1);for(let t=1;t{throw(0,re.n)("GroundMesh")},Zs._GoldbergMeshParser=(e,t)=>{throw(0,re.n)("GoldbergMesh")},Zs._LinesMeshParser=(e,t)=>{throw(0,re.n)("LinesMesh")},Zs._GreasedLineMeshParser=(e,t)=>{throw(0,re.n)("GreasedLineMesh")},Zs._GreasedLineRibbonMeshParser=(e,t)=>{throw(0,re.n)("GreasedLineRibbonMesh")},Zs._TrailMeshParser=(e,t)=>{throw(0,re.n)("TrailMesh")},d("BABYLON.Mesh",Zs);class Qs{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new se.cP,this._onDataLayoutChanged=new se.cP,this._animationPropertiesOverride=null,this._scene=i||_.q.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=he.Clone((()=>new Qs(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),he.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Qs(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t{const i=f.width,n=a(e);if(n){if(o){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const a=this._getRGBABufferInternalSizedFormat(r);let h=!1;t===u.RGB&&(t=u.RGBA,h=!0),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,f,!0),this._unpackFlipY(!1);const l=o(n);for(let s=0;s>s;for(let i=0;i<6;i++){let o=l[s][i];h&&(o=$s(o,n,n,r)),u.texImage2D(i,s,a,n,n,0,t,e,o)}}this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(f,n,s,r,d);f.isReady=!0,t?.removePendingData(f),f.onLoadedObservable.notifyObservers(f),f.onLoadedObservable.clear(),h&&h()}};return this._loadFile(e,(e=>{_(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(f),l&&e&&l(e.status+" "+e.statusText,i)})),f},Ke.w.prototype.createRawTexture2DArray=Js(!1),Ke.w.prototype.createRawTexture3D=Js(!0),Ke.w.prototype.updateRawTexture2DArray=er(!1),Ke.w.prototype.updateRawTexture3D=er(!0);class tr extends st{get depth(){return this._depth}constructor(e,t,i,s,r,n,a=!0,o=!1,h=st.TRILINEAR_SAMPLINGMODE,l=0,c){super(null,n,!a,o),this.format=r,this._texture=n.getEngine().createRawTexture2DArray(e,t,i,s,r,a,o,h,null,l,c),this._depth=s,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,s,r,n=!0,a=!1,o=3,h=0){return new tr(e,t,i,s,5,r,n,a,o,h)}}class ir{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new nt(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=_.q.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return ir.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new ir(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=ir.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void k.V.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new ir(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(Qs.Parse(s,t));return i}}ir.EnableTextureStorage=!0,ir.MaxActiveMorphTargetsInVertexAttributeMode=8,Zs._instancedMeshFactory=(e,t)=>{const i=new sr(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class sr extends Us{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 e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.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){this._sourceMesh?.receiveShadows!==e&&Xe.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Xe.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Xe.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Xe.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&&k.V.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||k.V.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!==ws.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new y);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,R.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(R.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&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;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 ar extends mi{constructor(e){super(),this._wasAddedToScene=!1,(e=e||_.q.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof sr){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(k.V.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>k.V.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Us&&-1!==this.meshes.indexOf(e)||e instanceof ws&&-1!==this.transformNodes.indexOf(e)||e instanceof Ze&&-1!==this.lights.indexOf(e)||e instanceof ni&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return k.V.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Xe.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new nr,a=[],o=[],h={doNotInstantiate:!0,...i},l=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(l,c,e,h.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(l,c,e,h.predicate);const d=this._topologicalSort(l),u=(i,a)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Zs){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===a.parent&&n.rootNodes.push(a)};return d.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],a=("number"==typeof n?r[n]:i).createInstance(t.name);u(t,a)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:h.doNotInstantiate&&(t="function"==typeof h.doNotInstantiate?!h.doNotInstantiate(e):!h.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);u(e,i)}})),this.skeletons.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==a.indexOf(i))continue;a.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Xe.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((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Xe.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 e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new rr);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Zs("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=_.q.LastCreatedScene,t,i=null){if(!e)return k.V.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof Zs?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof ws?this.transformNodes.push(e):e instanceof Ze?this.lights.push(e):e instanceof ni&&this.cameras.push(e),e instanceof Us){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class or extends ce{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,a=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??y.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new y,this._absoluteBindMatrix=new y,this._absoluteInverseBindMatrix=new y,this._finalMatrix=new y,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=R.Vector3[0],t=R.Quaternion[0],i=R.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??S.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=M.Zero(),this._localRotation=S.Zero(),this._localPosition=M.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,y.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e=0?n.referenceFrame:0;let h=0;const l=a._keys[0];let c=a._keys.length-1;const d=a._keys[c],u={referenceValue:l.value,referencePosition:R.Vector3[0],referenceQuaternion:R.Quaternion[0],referenceScaling:R.Vector3[1],keyPosition:R.Vector3[2],keyQuaternion:R.Quaternion[1],keyScaling:R.Vector3[3]};let f=l.frame,_=d.frame;if(n.range){const e=a.getRange(n.range);e&&(f=e.from,_=e.to)}else f=n.fromFrame??f,_=n.toFrame??_;if(f!==l.frame&&(h=a.createKeyForFrame(f)),_!==d.frame&&(c=a.createKeyForFrame(_)),1===a._keys.length){const e=a._getKeyValue(a._keys[0]);u.referenceValue=e.clone?e.clone():e}else if(o<=l.frame){const e=a._getKeyValue(l.value);u.referenceValue=e.clone?e.clone():e}else if(o>=d.frame){const e=a._getKeyValue(d.value);u.referenceValue=e.clone?e.clone():e}else{gr.key=0;const e=a._interpolate(o,gr);u.referenceValue=e.clone?e.clone():e}a.dataType===mr.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():a.dataType===mr.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace());let p=Number.MAX_VALUE;const g=n.clipKeys?[]:null;for(let e=h;e<=c;e++){let t=a._keys[e];if((g||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},g&&(p===Number.MAX_VALUE&&(p=t.frame),t.frame-=p,g.push(t))),!e||a.dataType===mr.ANIMATIONTYPE_FLOAT||t.value!==l.value)switch(a.dataType){case mr.ANIMATIONTYPE_MATRIX:t.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),y.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,t.value);break;case mr.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(t.value,t.value);break;case mr.ANIMATIONTYPE_VECTOR2:case mr.ANIMATIONTYPE_VECTOR3:case mr.ANIMATIONTYPE_COLOR3:case mr.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(u.referenceValue,t.value);break;case mr.ANIMATIONTYPE_SIZE:t.value.width-=u.referenceValue.width,t.value.height-=u.referenceValue.height;break;default:t.value-=u.referenceValue}}return g&&a.setKeys(g,!0),a}static TransitionTo(e,t,i,s,r,n,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;const h=r*(a/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const l=s.beginAnimation(i,0,h,!1);return l.onAnimationEnd=o,l}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?mr.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=mr._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 e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const a=s[n],o=s[n+1];if(i&&(e===a.frame||e===o.frame))return;const h=this._getKeyValue(a.value),l=this._getKeyValue(o.value);if(a.interpolation===Gs.STEP)return o.frame>e?h:l;const c=void 0!==a.outTangent&&void 0!==o.inTangent,d=o.frame-a.frame;let u=(e-a.frame)/d;const f=a.easingFunction||this.getEasingFunction();switch(null!==f&&(u=f.ease(u)),this.dataType){case mr.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(h,a.outTangent*d,l,o.inTangent*d,u):this.floatInterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case mr.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.quaternionInterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||cr).scale(t.repeatCount))}return e}case mr.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.vector3InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||dr).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.vector2InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||ur).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_SIZE:switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,l,u);case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,l,u).add((t.offsetValue||fr).scale(t.repeatCount))}break;case mr.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.color3InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||_r).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(h,a.outTangent.scale(d),l,o.inTangent.scale(d),u):this.color4InterpolateFunction(h,l,u);switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return e;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||pr).scale(t.repeatCount))}break}case mr.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case mr.ANIMATIONLOOPMODE_CYCLE:case mr.ANIMATIONLOOPMODE_CONSTANT:case mr.ANIMATIONLOOPMODE_YOYO:return mr.AllowMatricesInterpolation?this.matrixInterpolateFunction(h,l,u,t.workValue):h;case mr.ANIMATIONLOOPMODE_RELATIVE:case mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}}return 0}matrixInterpolateFunction(e,t,i,s){return mr.AllowMatrixDecomposeForInterpolation?s?(y.DecomposeLerpToRef(e,t,i,s),s):y.DecomposeLerp(e,t,i):s?(y.LerpToRef(e,t,i,s),s):y.Lerp(e,t,i)}clone(){const e=new mr(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){gr.key=0;const t=this._interpolate(e,gr,!0);if(!t)return this._keys[gr.key].frame===e?gr.key:gr.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(gr.key+1,0,i),gr.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&&(a=t.values[1]),t.values.length>=3&&(o=t.values[2]),t.values.length>=4&&(h=t.values[3]);break;case mr.ANIMATIONTYPE_QUATERNION:if(r=S.FromArray(t.values),t.values.length>=8){const e=S.FromArray(t.values.slice(4,8));e.equals(S.Zero())||(a=e)}if(t.values.length>=12){const e=S.FromArray(t.values.slice(8,12));e.equals(S.Zero())||(o=e)}t.values.length>=13&&(h=t.values[12]);break;case mr.ANIMATIONTYPE_MATRIX:r=y.FromArray(t.values),t.values.length>=17&&(h=t.values[16]);break;case mr.ANIMATIONTYPE_COLOR3:r=L.FromArray(t.values),t.values[3]&&(a=L.FromArray(t.values[3])),t.values[4]&&(o=L.FromArray(t.values[4])),t.values[5]&&(h=t.values[5]);break;case mr.ANIMATIONTYPE_COLOR4:r=N.FromArray(t.values),t.values[4]&&(a=N.FromArray(t.values[4])),t.values[5]&&(o=N.FromArray(t.values[5])),t.values[6]&&(h=N.FromArray(t.values[6]));break;case mr.ANIMATIONTYPE_VECTOR3:default:r=M.FromArray(t.values),t.values[3]&&(a=M.FromArray(t.values[3])),t.values[4]&&(o=M.FromArray(t.values[4])),t.values[5]&&(h=t.values[5])}const l={};l.frame=t.frame,l.value=r,null!=a&&(l.inTangent=a),null!=o&&(l.outTangent=o),null!=h&&(l.interpolation=h),s.push(l)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new pe;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new pe;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}mr._UniqueIdGenerator=0,mr.AllowMatricesInterpolation=!1,mr.AllowMatrixDecomposeForInterpolation=!0,mr.SnippetUrl="https://snippet.babylonjs.com",mr.ANIMATIONTYPE_FLOAT=0,mr.ANIMATIONTYPE_VECTOR3=1,mr.ANIMATIONTYPE_QUATERNION=2,mr.ANIMATIONTYPE_MATRIX=3,mr.ANIMATIONTYPE_COLOR3=4,mr.ANIMATIONTYPE_COLOR4=7,mr.ANIMATIONTYPE_VECTOR2=5,mr.ANIMATIONTYPE_SIZE=6,mr.ANIMATIONLOOPMODE_RELATIVE=0,mr.ANIMATIONLOOPMODE_CYCLE=1,mr.ANIMATIONLOOPMODE_CONSTANT=2,mr.ANIMATIONLOOPMODE_YOYO=4,mr.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,mr.CreateFromSnippetAsync=mr.ParseFromSnippetAsync,d("BABYLON.Animation",mr),ce._AnimationRangeFactory=(e,t,i)=>new lr(e,t,i);class Tr{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=y.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new se.cP,this.bones=[],this._scene=i||_.q.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,R.Matrix[1]),e._updateAbsoluteBindMatrices(R.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=hr.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=hr.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new Tr(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=M.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const a=t.rest?y.FromArray(t.rest):null,o=new or(t.name,i,n,y.FromArray(t.matrix),a,null,r);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(mr.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class xr{static Data=["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACMElEQVRYR+2Xv4pTQRTGf2dubhLdICiii2KnYKHVolhauKWPoGAnNr6BD6CvIVaihYuI2i1ia0BY0MZGRHQXjZj/mSPnnskfNWiWZUlzJ5k7M2cm833nO5Mziej2DWWJRUoCpQKlAntSQCqgw39/iUWAGmh37jrRnVsKlgpiqmkoGVABA7E57fvY+pJDdgKqF6HzFCSADkDq+F6AHABtQ+UMVE5D7zXod7fFNhTEckTbj5XQgHzNN+5tQvc5NG7C6BNkp6D3EmpXHDR+dQAjFLchW3VS9rlw3JBh+B7ys5Cf9z0GW1C/7P32AyBAOAz1q4jGliIH3YPuBnSfQX4OGreTIgEYQb/pBDtPnEQ4CivXYPAWBk13oHrB54yA9QuSn2H4AcKRpEILDt0BUzj+RLR1V5EqjD66NPRBVpLcQwjHoHYJOhsQv6U4mnzmrIXJCFr4LDwm/xBUoboG9XX4cc9VKdYoSA2yk5NQLJaKDUjTBoveG3Z2TElTxwjNK4M3LEZgUdDdruvcXzKBpStgp2NPiWi3ks9ZXxIoFVi+AvHLdc9TqtjL3/aYjpPlrzOcEnK62Szhimdd7xX232zFDTgtxezOu3WNMRLjiKgjtOhHVMd1loynVHvOgjuIIJMaELEqhJAV/RCSLbWTcfPFakFgFlALTRRvx+ok6Hlp/Q+v3fmx90bMyUzaEAhmM3KvHlXTL5DxnbGf/1M8RNNACLL5MNtPxP/mypJAqcDSFfgFhpYqWUzhTEAAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII="]}function Er(e){const t=(e=e.replace(/\\/g,"/")).split("/"),i=[];for(let e=0;e{this._createTexture(t,i,e,s,n,a,((e,t)=>{o?.(e,t)}))}),void 0,!0,!0,((e,t)=>{o?.(e?e.status+" "+e.statusText:"",t)}))}loadFromArrayBuffer(e){this._createTexture(this._scene,this._assetContainer,this.cacheKey,e,this._options,this._onLoad,((e,t)=>{this._onError?.(e,t)}))}_onDisposeCallback=null;registerOnDisposeCallback(e){this._onDisposeCallback=e,this._texture.onDisposeObservable.addOnce(e)}unregisterOnDisposeCallback(){const e=this._onDisposeCallback;return null===e?null:(this._onDisposeCallback=null,this._texture.onDisposeObservable.removeCallback(e),e)}_createTexture(e,t,i,s,r,n,a){e._blockEntityCollection=!!t;const o={noMipmap:r.noMipmap,invertY:r.invertY,samplingMode:r.samplingMode,onLoad:()=>{null===this._texture?null!==n&&Me.SetImmediate(n):n?.()},onError:a,buffer:s,deleteBuffer:r.deleteBuffer,format:r.format,mimeType:r.mimeType},h=this._texture=new st("data:"+i,e,o);h._parentContainer=t,e._blockEntityCollection=!1,t?.textures.push(h),h.name=i}get texture(){return this._texture}}class br{onModelTextureLoadedObservable=new Map;textureCache=new Map;_textureLoadInfoMap=new Map;_loadingModels=new Map;_errorTexturesReferenceCount=new Map;_incrementLeftLoadCount(e){let t=this._loadingModels.get(e);void 0===t&&(t=new vr(e),this._loadingModels.set(e,t)),t.leftLoadCount+=1;let i=this.onModelTextureLoadedObservable.get(e);return void 0===i&&(i=new se.cP,this.onModelTextureLoadedObservable.set(e,i)),t}_decrementLeftLoadCount(e){if(e.leftLoadCount-=1,!e.isRequesting&&0===e.leftLoadCount){this._removeErrorTexturesReferenceCount(e.uniqueId),this._loadingModels.delete(e.uniqueId);const t=this.onModelTextureLoadedObservable.get(e.uniqueId);t?.notifyObservers(),t?.clear(),this.onModelTextureLoadedObservable.delete(e.uniqueId)}}loadModelTexturesEnd(e){const t=this._loadingModels.get(e);if(void 0!==t&&(t.isRequesting=!1,0===t.leftLoadCount)){this._removeErrorTexturesReferenceCount(e),this._loadingModels.delete(e);const t=this.onModelTextureLoadedObservable.get(e);t?.notifyObservers(),t?.clear(),this.onModelTextureLoadedObservable.delete(e)}}_addErrorTextureReferenceCount(e,t){this._loadingModels.get(e).errorTextureDatas.push(t),this._errorTexturesReferenceCount.set(t,(this._errorTexturesReferenceCount.get(t)??0)+1)}_removeErrorTexturesReferenceCount(e){const t=this._loadingModels.get(e);for(let e=0;e{this._textureLoadInfoMap.delete(e.cacheKey),this.textureCache.delete(e.cacheKey),this._errorTexturesReferenceCount.delete(e)}))}_createTextureCacheKey(e,t){const i=e.lastIndexOf(".");let s="";return-1!==i&&(s=e.substring(i),e=e.substring(0,i)),e+ +(t.noMipmap??!1)+ +(t.invertY??!0)+(t.samplingMode??st.TRILINEAR_SAMPLINGMODE)+(t.format??Mi.TEXTUREFORMAT_RGBA)+s}async _loadTextureAsyncInternal(e,t,i,s,r,n,a){const o=this._incrementLeftLoadCount(e),h=this._createTextureCacheKey(t,a);let l=this._textureLoadInfoMap.get(h);void 0===l&&(l=new Ar,this._textureLoadInfoMap.set(h,l));let c=this.textureCache.get(h);if(void 0===c&&!l.hasLoadError){const o=null!==s?xr.Data[s]:t;c=new Mr(h,r,n,o,null!==i,a,(()=>{this._handleTextureOnDispose(c),l.hasLoadError=!1,l.observable.notifyObservers(!1),l.observable.clear()}),((t,i)=>{null!==c.texture&&this._handleTextureOnDispose(c),this._addErrorTextureReferenceCount(e,c),l.hasLoadError=!0,l.observable.notifyObservers(!0),l.observable.clear()})),this.textureCache.set(h,c);const d=i instanceof Blob?await i.arrayBuffer():i;null!==d&&c.loadFromArrayBuffer(d)}return null!==c.texture&&c.texture.isReady()?(this._decrementLeftLoadCount(o),l.hasLoadError?null:c.texture):new Promise((e=>{l.observable.addOnce((t=>{this._decrementLeftLoadCount(o),e(t?null:c.texture)}))}))}async loadTextureAsync(e,t,i,s,r,n){let a;"number"==typeof i?((i<-1||9this._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[Pr._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.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(((e,t)=>e.priority-t.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&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case Vs.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.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)=>{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 r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let a=s.getCustomCode(i)?.[t];if(a){if(s.resolveIncludes){if(null===n){const t=yt.w.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:gt.l.GetShadersRepository(t),includesShadersStore:gt.l.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,(0,Ae.Iq)(a,n,(e=>a=e))}r+=a+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=Cr.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let a=n.exec(i);for(;null!==a;){let e=r;for(let t=0;t{Dr.length=0,Or=!1,Ws.OnEventObservable.remove(Fr),Fr=null}));const Dr=[];let Or=!1,Fr=null;class wr{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new Pr(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){he.Clone((()=>e),this)}serialize(){return he.Serialize(this)}parse(e,t,i){he.Parse((()=>this),e,t,i)}}z([q()],wr.prototype,"name",void 0),z([q()],wr.prototype,"priority",void 0),z([q()],wr.prototype,"resolveIncludes",void 0),z([q()],wr.prototype,"registerForExtraEvents",void 0),d("BABYLON.MaterialPluginBase",wr);class Lr extends yr{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class Nr extends wr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new Lr,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ws.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&&Rr.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&Rr.DetailTextureEnabled&&this._isEnabled?(Wt(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&&Rr.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Xt(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Rr.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){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}z([j("detailTexture"),Y("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"texture",void 0),z([q()],Nr.prototype,"diffuseBlendLevel",void 0),z([q()],Nr.prototype,"roughnessBlendLevel",void 0),z([q()],Nr.prototype,"bumpLevel",void 0),z([q(),Y("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"normalBlendMethod",void 0),z([q(),Y("_markAllSubMeshesAsTexturesDirty")],Nr.prototype,"isEnabled",void 0);const Br={effect:null,subMesh:null};class Ur extends yr{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class kr extends Ir{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new L(0,0,0),this.diffuseColor=new L(1,1,1),this.specularColor=new L(1,1,1),this.emissiveColor=new L(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new nt(16),this._worldViewProjectionMatrix=y.Zero(),this._globalAmbientColor=new L(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Nr(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Sr,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),kr.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),kr.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!!(kr.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(kr.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Ws.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ws.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}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(Vs.GetDefineNames,this._eventInfo),t.materialDefines=new Ur(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const a=r.getEngine();n._needNormals=function(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0;const o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(qt(e,t,n,a,i,s,o),a++,a===r)break;i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}(r,n);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(function(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===st.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case st.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case st.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case st.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case st.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case st.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case st.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case st.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case st.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case st.CUBIC_MODE:case st.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&kr.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;Wt(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&kr.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;Wt(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&kr.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;Wt(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&kr.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;Wt(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&kr.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(kr.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),function(e,t,i,s,r,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=s,a.FOG=r&&function(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),function(e,t,i,s,r,n=null,a=!1){let o=function(e,t){let i=!1;if(e.activeCamera){const s=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=1===e.activeCamera.mode?1:0,a=0===e.activeCamera.mode?1:0;(s^n||r^a)&&(t.CAMERA_ORTHOGRAPHIC=1===n,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}(e,s);!1!==n&&(o=function(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),a=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),h=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==a&&(i.CLIPPLANE3=a,s=!0),i.CLIPPLANE4!==o&&(i.CLIPPLANE4=o,s=!0),i.CLIPPLANE5!==h&&(i.CLIPPLANE5=h,s=!0),i.CLIPPLANE6!==l&&(i.CLIPPLANE6=l,s=!0),s}(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,o=!0),s.INSTANCES!==r&&(s.INSTANCES=r,o=!0),s.THIN_INSTANCES!==a&&(s.THIN_INSTANCES=a,o=!0),o&&s.markAsUnprocessed()}(r,a,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),function(e,t,i,s,r=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&function(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}(e,t),r&&function(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}(e,t),a&&function(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}(e,t)}(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let h=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new Ct;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),function(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));r++}(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const o=[G.PositionKind];n.NORMAL&&o.push(G.NormalKind),n.TANGENT&&o.push(G.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&o.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&o.push(G.ColorKind),function(e,t,i,s){i.NUM_BONE_INFLUENCERS>0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}(o,e,n,s),function(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Vt(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}(o,n),kt(o,e,n),Ht(o,0,n);let l="default";const c=["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"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],u=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=o,this._eventInfo.samplers=d,this._eventInfo.uniformBuffersNames=u,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(Vs.PrepareEffect,this._eventInfo),Sr.AddUniforms(c),Sr.AddSamplers(d),Ii&&(Ii.PrepareUniforms(c,n),Ii.PrepareSamplers(d,n)),function(e,t,i,s=4){let r,n=null;if(e.uniformsNames){const a=e;r=a.uniformsNames,n=a.uniformBuffersNames,t=a.samplers,i=a.defines,s=a.maxSimultaneousLights||0}else r=e,t||(t=[]);for(let e=0;e0&&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){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=he.Clone((()=>new kr(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=he.Parse((()=>new kr(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Ws._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return Rr.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Rr.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Rr.DetailTextureEnabled}static set DetailTextureEnabled(e){Rr.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Rr.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Rr.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Rr.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Rr.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Rr.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Rr.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Rr.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Rr.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Rr.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Rr.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Rr.BumpTextureEnabled}static set BumpTextureEnabled(e){Rr.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Rr.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Rr.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Rr.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Rr.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Rr.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Rr.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Rr.FresnelEnabled}static set FresnelEnabled(e){Rr.FresnelEnabled=e}}z([j("diffuseTexture")],kr.prototype,"_diffuseTexture",void 0),z([Y("_markAllSubMeshesAsTexturesAndMiscDirty")],kr.prototype,"diffuseTexture",void 0),z([j("ambientTexture")],kr.prototype,"_ambientTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"ambientTexture",void 0),z([j("opacityTexture")],kr.prototype,"_opacityTexture",void 0),z([Y("_markAllSubMeshesAsTexturesAndMiscDirty")],kr.prototype,"opacityTexture",void 0),z([j("reflectionTexture")],kr.prototype,"_reflectionTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"reflectionTexture",void 0),z([j("emissiveTexture")],kr.prototype,"_emissiveTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"emissiveTexture",void 0),z([j("specularTexture")],kr.prototype,"_specularTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"specularTexture",void 0),z([j("bumpTexture")],kr.prototype,"_bumpTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"bumpTexture",void 0),z([j("lightmapTexture")],kr.prototype,"_lightmapTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"lightmapTexture",void 0),z([j("refractionTexture")],kr.prototype,"_refractionTexture",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"refractionTexture",void 0),z([Z("ambient")],kr.prototype,"ambientColor",void 0),z([Z("diffuse")],kr.prototype,"diffuseColor",void 0),z([Z("specular")],kr.prototype,"specularColor",void 0),z([Z("emissive")],kr.prototype,"emissiveColor",void 0),z([q()],kr.prototype,"specularPower",void 0),z([q("useAlphaFromDiffuseTexture")],kr.prototype,"_useAlphaFromDiffuseTexture",void 0),z([Y("_markAllSubMeshesAsTexturesAndMiscDirty")],kr.prototype,"useAlphaFromDiffuseTexture",void 0),z([q("useEmissiveAsIllumination")],kr.prototype,"_useEmissiveAsIllumination",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useEmissiveAsIllumination",void 0),z([q("linkEmissiveWithDiffuse")],kr.prototype,"_linkEmissiveWithDiffuse",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"linkEmissiveWithDiffuse",void 0),z([q("useSpecularOverAlpha")],kr.prototype,"_useSpecularOverAlpha",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useSpecularOverAlpha",void 0),z([q("useReflectionOverAlpha")],kr.prototype,"_useReflectionOverAlpha",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useReflectionOverAlpha",void 0),z([q("disableLighting")],kr.prototype,"_disableLighting",void 0),z([Y("_markAllSubMeshesAsLightsDirty")],kr.prototype,"disableLighting",void 0),z([q("useObjectSpaceNormalMap")],kr.prototype,"_useObjectSpaceNormalMap",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useObjectSpaceNormalMap",void 0),z([q("useParallax")],kr.prototype,"_useParallax",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useParallax",void 0),z([q("useParallaxOcclusion")],kr.prototype,"_useParallaxOcclusion",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useParallaxOcclusion",void 0),z([q()],kr.prototype,"parallaxScaleBias",void 0),z([q("roughness")],kr.prototype,"_roughness",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"roughness",void 0),z([q()],kr.prototype,"indexOfRefraction",void 0),z([q()],kr.prototype,"invertRefractionY",void 0),z([q()],kr.prototype,"alphaCutOff",void 0),z([q("useLightmapAsShadowmap")],kr.prototype,"_useLightmapAsShadowmap",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useLightmapAsShadowmap",void 0),z([Q("diffuseFresnelParameters")],kr.prototype,"_diffuseFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"diffuseFresnelParameters",void 0),z([Q("opacityFresnelParameters")],kr.prototype,"_opacityFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelAndMiscDirty")],kr.prototype,"opacityFresnelParameters",void 0),z([Q("reflectionFresnelParameters")],kr.prototype,"_reflectionFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"reflectionFresnelParameters",void 0),z([Q("refractionFresnelParameters")],kr.prototype,"_refractionFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"refractionFresnelParameters",void 0),z([Q("emissiveFresnelParameters")],kr.prototype,"_emissiveFresnelParameters",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"emissiveFresnelParameters",void 0),z([q("useReflectionFresnelFromSpecular")],kr.prototype,"_useReflectionFresnelFromSpecular",void 0),z([Y("_markAllSubMeshesAsFresnelDirty")],kr.prototype,"useReflectionFresnelFromSpecular",void 0),z([q("useGlossinessFromSpecularMapAlpha")],kr.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"useGlossinessFromSpecularMapAlpha",void 0),z([q("maxSimultaneousLights")],kr.prototype,"_maxSimultaneousLights",void 0),z([Y("_markAllSubMeshesAsLightsDirty")],kr.prototype,"maxSimultaneousLights",void 0),z([q("invertNormalMapX")],kr.prototype,"_invertNormalMapX",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"invertNormalMapX",void 0),z([q("invertNormalMapY")],kr.prototype,"_invertNormalMapY",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"invertNormalMapY",void 0),z([q("twoSidedLighting")],kr.prototype,"_twoSidedLighting",void 0),z([Y("_markAllSubMeshesAsTexturesDirty")],kr.prototype,"twoSidedLighting",void 0),z([q("applyDecalMapAfterDetailMap")],kr.prototype,"_applyDecalMapAfterDetailMap",void 0),z([Y("_markAllSubMeshesAsMiscDirty")],kr.prototype,"applyDecalMapAfterDetailMap",void 0),d("BABYLON.StandardMaterial",kr),as.DefaultMaterialFactory=e=>new kr("default material",e);class Vr extends yr{SPHERE_TEXTURE=!1;SPHERE_TEXTURE_BLEND_MODE_MULTIPLY=!1;SPHERE_TEXTURE_BLEND_MODE_ADD=!1;TOON_TEXTURE=!1;IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED=!1;APPLY_AMBIENT_COLOR_TO_DIFFUSE=!1;TEXTURE_COLOR=!1;SPHERE_TEXTURE_COLOR=!1;TOON_TEXTURE_COLOR=!1;SDEF=!1}var Gr;!function(e){e[e.Multiply=1]="Multiply",e[e.Add=2]="Add",e[e.SubTexture=3]="SubTexture"}(Gr||(Gr={}));class zr extends wr{_sphereTexture=null;_sphereTextureBlendMode=Gr.Add;_toonTexture=null;_ignoreDiffuseWhenToonTextureIsNull=!1;textureMultiplicativeColor=new N(1,1,1,1);textureAdditiveColor=new N(0,0,0,0);sphereTextureMultiplicativeColor=new N(1,1,1,1);sphereTextureAdditiveColor=new N(0,0,0,0);toonTextureMultiplicativeColor=new N(1,1,1,1);toonTextureAdditiveColor=new N(0,0,0,0);_applyAmbientColorToDiffuse=!0;_useTextureColor=!1;_useSphereTextureColor=!1;_useToonTextureColor=!1;_isEnabled=!1;get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this.markAllDefinesAsDirty(),this._enable(e))}get sphereTexture(){return this._sphereTexture}set sphereTexture(e){this._sphereTexture!==e&&(this._sphereTexture=e,this.markAllSubMeshesAsTexturesDirty())}get sphereTextureBlendMode(){return this._sphereTextureBlendMode}set sphereTextureBlendMode(e){this._sphereTextureBlendMode!==e&&(this._sphereTextureBlendMode=e,this.markAllDefinesAsDirty())}get toonTexture(){return this._toonTexture}set toonTexture(e){this._toonTexture!==e&&(this._toonTexture=e,this.markAllSubMeshesAsTexturesDirty())}get ignoreDiffuseWhenToonTextureIsNull(){return this._ignoreDiffuseWhenToonTextureIsNull}set ignoreDiffuseWhenToonTextureIsNull(e){this._ignoreDiffuseWhenToonTextureIsNull!==e&&(this._ignoreDiffuseWhenToonTextureIsNull=e,this.markAllDefinesAsDirty())}get applyAmbientColorToDiffuse(){return this._applyAmbientColorToDiffuse}set applyAmbientColorToDiffuse(e){this._applyAmbientColorToDiffuse!==e&&(this._applyAmbientColorToDiffuse=e,this.markAllDefinesAsDirty())}get useTextureColor(){return this._useTextureColor}set useTextureColor(e){this._useTextureColor!==e&&(this._useTextureColor=e,this.markAllDefinesAsDirty())}get useSphereTextureColor(){return this._useSphereTextureColor}set useSphereTextureColor(e){this._useSphereTextureColor!==e&&(this._useSphereTextureColor=e,this.markAllDefinesAsDirty())}get useToonTextureColor(){return this._useToonTextureColor}set useToonTextureColor(e){this._useToonTextureColor!==e&&(this._useToonTextureColor=e,this.markAllDefinesAsDirty())}_internalMarkAllSubMeshesAsTexturesDirty;markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"MmdMaterial",100,new Vr,t),this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Mi.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._sphereTexture&&!this._sphereTexture.isReadyOrNotBlocking())}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||(r.DIFFUSE&&r.TEXTURE_COLOR&&(e.updateDirectColor4("textureMultiplicativeColor",this.textureMultiplicativeColor),e.updateDirectColor4("textureAdditiveColor",this.textureAdditiveColor)),r.NORMAL&&r.SPHERE_TEXTURE&&r.SPHERE_TEXTURE_COLOR&&(e.updateDirectColor4("sphereTextureMultiplicativeColor",this.sphereTextureMultiplicativeColor),e.updateDirectColor4("sphereTextureAdditiveColor",this.sphereTextureAdditiveColor)),r.TOON_TEXTURE&&r.TOON_TEXTURE_COLOR&&(e.updateDirectColor4("toonTextureMultiplicativeColor",this.toonTextureMultiplicativeColor),e.updateDirectColor4("toonTextureAdditiveColor",this.toonTextureAdditiveColor)),r.SPHERE_TEXTURE&&null!==s.effect&&this._material.bindView(s.effect)),t.texturesEnabled&&(r.NORMAL&&this._sphereTexture&&e.setTexture("sphereSampler",this._sphereTexture),this._toonTexture&&e.setTexture("toonSampler",this._toonTexture))}dispose(e){e&&(this._sphereTexture?.dispose(),this._toonTexture?.dispose())}getCustomCode(e){if("vertex"===e){const e={};return e.CUSTOM_VERTEX_DEFINITIONS=hs,e[`!${this._escapeRegExp("finalWorld=finalWorld*influence;")}`]=`\n${ls}\nfinalWorld=(finalWorld*influence);\n`,e}if("fragment"===e){const e={CUSTOM_FRAGMENT_DEFINITIONS:"\n#if defined(SPHERE_TEXTURE) && defined(NORMAL)\nuniform sampler2D sphereSampler;\n#endif\n#ifdef TOON_TEXTURE\nuniform sampler2D toonSampler;\n#endif\n",CUSTOM_FRAGMENT_MAIN_BEGIN:"\n#ifdef TOON_TEXTURE\nvec3 toonNdl;\n#endif\n"};e[`!${this._escapeRegExp("#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif")}`]="\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#elif defined(NORMAL) && defined(SPHERE_TEXTURE)\nuniform mat4 view;\n#endif\n",e[`!${this._escapeRegExp("vec3 diffuseColor=vDiffuseColor.rgb;")}`]="\n#ifdef APPLY_AMBIENT_COLOR_TO_DIFFUSE\nvec3 diffuseColor=clamp(vDiffuseColor.rgb+vAmbientColor,0.0,1.0);\n#else\nvec3 diffuseColor=(vDiffuseColor.rgb);\n#endif\n",e[`!${this._escapeRegExp("baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);")}`]="\n#if defined(DIFFUSE) && defined(TEXTURE_COLOR)\nbaseColor=texture2D(diffuseSampler,(vDiffuseUV+uvOffset));baseColor.rgb=mix(\nvec3(1.0),\nbaseColor.rgb*textureMultiplicativeColor.rgb,\ntextureMultiplicativeColor.a\n);baseColor.rgb=clamp(\nbaseColor.rgb+(baseColor.rgb-vec3(1.0))*textureAdditiveColor.a,\n0.0,\n1.0\n)+textureAdditiveColor.rgb;\n#else\nbaseColor=texture2D(diffuseSampler,(vDiffuseUV+uvOffset));\n#endif\n",e[`!${this._escapeRegExp("struct lightingInfo\n{")}`]="\nstruct lightingInfo {\n#ifdef TOON_TEXTURE\n#if !defined(NDOTL)\nfloat ndl;\n#endif\nfloat isToon;\n#endif\n",e[`!${this._escapeRegExp("result.diffuse=ndl*diffuseColor*attenuation;")}`]="\n#ifdef TOON_TEXTURE\nresult.diffuse=diffuseColor*attenuation;result.ndl=ndl;result.isToon=1.0;\n#elif defined(IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED) \nresult.diffuse=diffuseColor*attenuation;\n#else\nresult.diffuse=(ndl*diffuseColor*attenuation);\n#endif\n",e[`!${this._escapeRegExp("diffuseBase+=info.diffuse*shadow;")}`]="\n#ifdef TOON_TEXTURE\ntoonNdl=vec3(clamp(info.ndl*shadow,0.02,0.98));toonNdl.r=texture2D(toonSampler,vec2(0.5,toonNdl.r)).r;toonNdl.g=texture2D(toonSampler,vec2(0.5,toonNdl.g)).g;toonNdl.b=texture2D(toonSampler,vec2(0.5,toonNdl.b)).b;\n#ifdef TOON_TEXTURE_COLOR\ntoonNdl=mix(\nvec3(1.0),\ntoonNdl*toonTextureMultiplicativeColor.rgb,\ntoonTextureMultiplicativeColor.a\n);toonNdl=clamp(\ntoonNdl+(toonNdl-vec3(1.0))*toonTextureAdditiveColor.a,\n0.0,\n1.0\n)+toonTextureAdditiveColor.rgb;\n#endif\ndiffuseBase+=mix(info.diffuse*shadow,toonNdl*info.diffuse,info.isToon);\n#elif defined(IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED)\ndiffuseBase+=info.diffuse;\n#else\ndiffuseBase+=(info.diffuse*shadow);\n#endif\n";const t="\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n";return e[`!${this._escapeRegExp(t)}`]=`\n#ifdef APPLY_AMBIENT_COLOR_TO_DIFFUSE\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#else\n${t.replace("diffuseBase","(diffuseBase)")}#endif\n`,e.CUSTOM_FRAGMENT_BEFORE_FOG="\n#if defined(NORMAL) && defined(SPHERE_TEXTURE)\nvec3 viewSpaceNormal=normalize(mat3(view)*vNormalW);vec2 sphereUV=viewSpaceNormal.xy*0.5+0.5;vec4 sphereReflectionColor=texture2D(sphereSampler,sphereUV);\n#ifdef SPHERE_TEXTURE_COLOR\nsphereReflectionColor.rgb=mix(\nvec3(1.0),\nsphereReflectionColor.rgb*sphereTextureMultiplicativeColor.rgb,\nsphereTextureMultiplicativeColor.a\n);sphereReflectionColor.rgb=clamp(\nsphereReflectionColor.rgb+(sphereReflectionColor.rgb-vec3(1.0))*sphereTextureAdditiveColor.a,\n0.0,\n1.0\n)+sphereTextureAdditiveColor.rgb;\n#endif\nsphereReflectionColor.rgb*=diffuseBase;\n#ifdef SPHERE_TEXTURE_BLEND_MODE_MULTIPLY\ncolor*=sphereReflectionColor;\n#elif defined(SPHERE_TEXTURE_BLEND_MODE_ADD)\ncolor=vec4(color.rgb+sphereReflectionColor.rgb,color.a);\n#endif\n#endif\n",e}return null}prepareDefines(e,t,i){if(this._isEnabled){const s=t.texturesEnabled;e.SPHERE_TEXTURE=null!==this._sphereTexture&&s,e.SPHERE_TEXTURE_BLEND_MODE_MULTIPLY=this._sphereTextureBlendMode===Gr.Multiply,e.SPHERE_TEXTURE_BLEND_MODE_ADD=this._sphereTextureBlendMode===Gr.Add,e.TOON_TEXTURE=null!==this._toonTexture&&s,e.IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED=this._ignoreDiffuseWhenToonTextureIsNull,e.APPLY_AMBIENT_COLOR_TO_DIFFUSE=this._applyAmbientColorToDiffuse,e.TEXTURE_COLOR=this._useTextureColor,e.SPHERE_TEXTURE_COLOR=this._useSphereTextureColor,e.TOON_TEXTURE_COLOR=this._useToonTextureColor,e.SDEF=i.useBones&&i.computeBonesUsingShaders&&!!i.skeleton&&i.isVerticesDataPresent(os.MatricesSdefCKind)}else e.SPHERE_TEXTURE=!1,e.SPHERE_TEXTURE_BLEND_MODE_MULTIPLY=!1,e.SPHERE_TEXTURE_BLEND_MODE_ADD=!1,e.TOON_TEXTURE=!1,e.IGNORE_DIFFUSE_WHEN_TOON_TEXTURE_DISABLED=!1,e.APPLY_AMBIENT_COLOR_TO_DIFFUSE=!1,e.TEXTURE_COLOR=!1,e.SPHERE_TEXTURE_COLOR=!1,e.TOON_TEXTURE_COLOR=!1,e.SDEF=!1}hasTexture(e){return this._sphereTexture===e||this._toonTexture===e}getActiveTextures(e){this._sphereTexture&&e.push(this._sphereTexture),this._toonTexture&&e.push(this._toonTexture)}getAnimatables(e){this._sphereTexture&&this._sphereTexture.animations&&0(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),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(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){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 r=this.getScene(),n=r.getEngine(),a=[],o=[],h=new Ct;let l=this._shaderPath,c=this._options.uniforms,d=this._options.uniformBuffers,u=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,a.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(o.push(G.MatricesIndicesExtraKind),o.push(G.MatricesWeightsExtraKind));const t=e.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),h.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(a.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(a.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else a.push("#define NUM_BONE_INFLUENCERS 0");let f=0;const _=e?e.morphTargetManager:null;if(_){const e=_.supportsUVs&&-1!==a.indexOf("#define UV1"),t=_.supportsTangents&&-1!==a.indexOf("#define TANGENT"),i=_.supportsNormals&&-1!==a.indexOf("#define NORMAL");f=_.numMaxInfluencers||_.numInfluencers,e&&a.push("#define MORPHTARGETS_UV"),t&&a.push("#define MORPHTARGETS_TANGENT"),i&&a.push("#define MORPHTARGETS_NORMAL"),f>0&&a.push("#define MORPHTARGETS"),_.isUsingTextureForTargets&&(a.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),a.push("#define NUM_MORPH_INFLUENCERS "+f);for(let s=0;s0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else a.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),Ht(o,0,a)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&a.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(Pt(c),Dt(this,r,a)),r.fogEnabled&&e?.applyFog&&r.fogMode!==as.FOGMODE_NONE&&(a.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(a.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),d=d.slice(),u=u.slice(),l=this.customShaderNameResolve(this.name,c,d,u,a,o));const p=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,g=p?.effect??null,m=p?.defines??null,T=a.join("\n");let x=g;return m!==T&&(x=n.createEffect(l,{attributes:o,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:T,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:f},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,T,this._materialContext):p&&p.setEffect(x,T),this._onEffectCreatedObservable&&(Hr.effect=x,Hr.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(Hr))),p._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(g!==x&&r.resetCachedMaterial(),p._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const a=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const o=this._options.uniformBuffers;let h=!1;if(n&&o&&o.length>0&&a.getEngine().supportsUniformBuffers)for(let i=0;i0&&Gt(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,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 t=0;tnew Kr(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Kr(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,st.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],a=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>L.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,N.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>N.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,A.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,M.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,b.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,S.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,y.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const a=new pe;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const t=JSON.parse(a.responseText),n=this.Parse(t,i||_.q.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),a.open("GET",t),a.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new pe;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(r.shaderMaterial),o=this.Parse(a,t||_.q.LastCreatedScene,i);o.snippetId=e,s(o)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}var Yr,qr,jr;Kr.SnippetUrl="https://snippet.babylonjs.com",Kr.CreateFromSnippetAsync=Kr.ParseFromSnippetAsync,d("BABYLON.ShaderMaterial",Kr),function(e){e[e.Opaque=Ws.MATERIAL_OPAQUE]="Opaque",e[e.AlphaTest=Ws.MATERIAL_ALPHATEST]="AlphaTest",e[e.AlphaBlend=Ws.MATERIAL_ALPHABLEND]="AlphaBlend"}(Yr||(Yr={}));class Zr{_scene;_renderTargetTexture;_resultPixelsBuffer;constructor(e,t=512){this._scene=e;const i=e.getEngine(),s=this._renderTargetTexture=new St("texture_alpha_checker",t,e,{generateDepthBuffer:!1,generateStencilBuffer:!1,generateMipMaps:!1,type:Mi.TEXTURETYPE_UNSIGNED_BYTE,format:i.isWebGPU||i.version>1?Mi.TEXTUREFORMAT_RED:Mi.TEXTUREFORMAT_RGBA,doNotChangeAspectRatio:!0});s.noPrePassRenderer=!0,s.anisotropicFilteringLevel=1,s.renderParticles=!1,s.optimizeUVAllocation=!0,s.ignoreCameraViewport=!0,s.clearColor=new N(0,0,0,1),this._resultPixelsBuffer=new Uint8Array(t*t*4)}async _renderTexture(e,t,i){const s=Zr._GetShader(this._scene);s.setTexture("textureSampler",e);let r=null;null!==i&&(r=t.subMeshes,t.subMeshes=[t.subMeshes[i]]);const n=this._renderTargetTexture;n.renderList=[t],n.setMaterialForRendering(t,s);const a=t._internalAbstractMeshDataInfo._currentLODIsUpToDate,o=t._internalAbstractMeshDataInfo._currentLOD;t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,t._internalAbstractMeshDataInfo._currentLOD=t;const h=t._nodeDataStorage._isEnabled,l=t._nodeDataStorage._isParentEnabled;t._nodeDataStorage._isEnabled=!0,t._nodeDataStorage._isParentEnabled=!0,n.render(!1,!1),t._nodeDataStorage._isParentEnabled=l,t._nodeDataStorage._isEnabled=h,t._internalAbstractMeshDataInfo._currentLOD=o,t._internalAbstractMeshDataInfo._currentLODIsUpToDate=a;const c=s.getEffect();t.geometry._releaseVertexArrayObject(c);const d=t.subMeshes;for(let e=0,t=d.length;e{this._taskQueue.push(e)})),this._blockRendering=!0;const n=await this._renderTexture(e,t,i);let a=0,o=0,h=0;for(let e=0;e{this._taskQueue.push(e)})),this._blockRendering=!0;const s=await this._renderTexture(e,t,i);for(let e=0;e{e._textureAlphaCheckerShader?.dispose(),e._textureAlphaCheckerShader=null})),e._textureAlphaCheckerShader=t}return e._textureAlphaCheckerShader}static DisposeShader(e){e._textureAlphaCheckerShader?.dispose(),e._textureAlphaCheckerShader=null}}!function(e){e[e.DepthWriteAlphaBlendingWithEvaluation=0]="DepthWriteAlphaBlendingWithEvaluation",e[e.DepthWriteAlphaBlending=1]="DepthWriteAlphaBlending",e[e.AlphaEvaluation=2]="AlphaEvaluation"}(qr||(qr={}));class Qr{renderMethod=qr.DepthWriteAlphaBlendingWithEvaluation;forceDisableAlphaEvaluation=!1;alphaThreshold=195;alphaBlendThreshold=100;alphaEvaluationResolution=512;deleteTextureBufferAfterLoad=!0;_textureLoader=new br;nextStartingAlphaIndex=65536;alphaIndexIncrementsPerModel=1024;_setMeshesAlphaIndex(e){let t=this.nextStartingAlphaIndex;for(let i=0;inull!==g?g:this.forceDisableAlphaEvaluation?null:g=new Zr(l,this.alphaEvaluationResolution),T=new Xr(a,r,n),x=[],E={lengthComputable:!0,loaded:0,total:3*t.length},v=()=>{E.loaded+=1,f?.(E)},A=[];for(let n=0;nthis.setAlphaBlendMode(h,a,o[n],u,m);if(void 0!==f){const e=f.then(_);t.push(e)}else{const e=_();void 0!==e&&t.push(e)}const p=this.loadSphereTexture(e,h,a,s,i[a.sphereTextureIndex]??null,l,c,r,T,u,v);void 0!==p&&t.push(p);const g=this.loadToonTexture(e,h,a,s,i[a.toonTextureIndex]??null,l,c,r,T,u,v);void 0!==g&&t.push(g);const E=this.loadOutlineRenderingProperties(h,a,u);void 0!==E&&t.push(E),x.push(...t),Promise.all(t).then((()=>{this.afterBuildSingleMaterial(h,n,a,s,i,l,r)}))}A.push(h)}this._textureLoader.loadModelTexturesEnd(e);const M=this._textureLoader.onModelTextureLoadedObservable.get(e);return void 0!==M?M.addOnce((()=>{Promise.all(x).then((()=>{g?.dispose(),l._forceBlockMaterialDirtyMechanism(p),null!==d&&this._buildTextureNameMap(t,A,s,i,d),_?.()}))})):Promise.all(x).then((()=>{g?.dispose(),l._forceBlockMaterialDirtyMechanism(p),null!==d&&this._buildTextureNameMap(t,A,s,i,d),_?.()})),A}_buildTextureNameMap(e,t,i,s,r){for(let n=0;n{const s=t.diffuse;e.diffuseColor=new L(s[0],s[1],s[2]);const r=t.specular;e.specularColor=new L(r[0],r[1],r[2]);const n=t.ambient;e.ambientColor=new L(n[0],n[1],n[2]);const a=t.diffuse[3];if(e.alpha=a,0===a)for(let e=0;e{t.backFaceCulling=!(i.flag&ps.Material.Flag.IsDoubleSided);const d=s[r?.imagePathIndex??-1];if(void 0!==d){const i=h.createFullPath(d);let s;const u=h.resolve(i);s=void 0!==u?await this._textureLoader.loadTextureFromBufferAsync(e,i,u instanceof File?u:u.data,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:Mi.TEXTUREFORMAT_RGBA,mimeType:u instanceof File?u.type:u.mimeType}):await this._textureLoader.loadTextureAsync(e,o,d,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:Mi.TEXTUREFORMAT_RGBA});const f=s;null!==f?t.diffuseTexture=f:l.error(`Failed to load diffuse texture: ${i}`),c?.()}else c?.()};async _evaluateDiffuseTextureTransparencyMode(e,t,i,s,r){let n=Number.MIN_SAFE_INTEGER;if(this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation){let s=t>>4&3;if(0==(3^s)&&(s=-1),-1===s){n=Ws.MATERIAL_OPAQUE;const t=r();if(null!==t)for(let s=0;s{if(this.renderMethod===qr.DepthWriteAlphaBlending)return e.diffuseTexture&&(e.diffuseTexture.hasAlpha=!0,e.useAlphaFromDiffuseTexture=!0),e.transparencyMode=Ws.MATERIAL_ALPHABLEND,void(e.forceDepthWrite=!0);if(this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation&&e.alpha<1)return e.diffuseTexture&&(e.diffuseTexture.hasAlpha=!0,e.useAlphaFromDiffuseTexture=!0),e.transparencyMode=Ws.MATERIAL_ALPHABLEND,void(e.forceDepthWrite=!0);const n=e.diffuseTexture,a=t.evaluatedTransparency??-1;if(null!==n){const t=await this._evaluateDiffuseTextureTransparencyMode(n,a,i,s,r);if(null!==t){const i=t!==Ws.MATERIAL_OPAQUE;i&&(n.hasAlpha=!0),e.useAlphaFromDiffuseTexture=i,e.transparencyMode=t,this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation&&(e.forceDepthWrite=i)}}else if(this.renderMethod===qr.DepthWriteAlphaBlendingWithEvaluation){let t=a>>4&3;0==(3^t)&&(t=0),e.transparencyMode=0===t?Ws.MATERIAL_OPAQUE:Ws.MATERIAL_ALPHABLEND}else{let t=15&a;0==(15^t)&&(t=0),e.transparencyMode=Ws.MATERIAL_OPAQUE}};loadSphereTexture=async(e,t,i,s,r,n,a,o,h,l,c)=>{if(i.sphereTextureMode!==ps.Material.SphereTextureMode.Off){const d=s[r?.imagePathIndex??-1];if(void 0!==d){const s=n.getEngine().isWebGPU||i.sphereTextureMode===ps.Material.SphereTextureMode.Multiply?Mi.TEXTUREFORMAT_RGBA:Mi.TEXTUREFORMAT_RGB,u=h.createFullPath(d);let f;const _=h.resolve(u);f=void 0!==_?await this._textureLoader.loadTextureFromBufferAsync(e,u,_ instanceof File?_:_.data,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:s,mimeType:_ instanceof File?_.type:_.mimeType}):await this._textureLoader.loadTextureAsync(e,o,d,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:s}),null!==f?(t.sphereTexture=f,t.sphereTextureBlendMode=i.sphereTextureMode):l.error(`Failed to load sphere texture: ${u}`),c?.()}else c?.()}else c?.()};loadToonTexture=async(e,t,i,s,r,n,a,o,h,l,c)=>{let d;if(d=i.isSharedToonTexture?i.toonTextureIndex:s[r?.imagePathIndex??-1],void 0!==d){const i=h.createFullPath(d.toString());let s;const u="string"==typeof d?h.resolve(i):void 0;s=void 0!==u?await this._textureLoader.loadTextureFromBufferAsync(e,i,u instanceof File?u:u.data,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:n.getEngine().isWebGPU?Mi.TEXTUREFORMAT_RGBA:Mi.TEXTUREFORMAT_RGB,mimeType:u instanceof File?u.type:u.mimeType}):await this._textureLoader.loadTextureAsync(e,o,d,n,a,{...r,deleteBuffer:this.deleteTextureBufferAfterLoad,format:n.getEngine().isWebGPU?Mi.TEXTUREFORMAT_RGBA:Mi.TEXTUREFORMAT_RGB}),null!==s?t.toonTexture=s:l.error(`Failed to load toon texture: ${i}`),c?.()}else c?.()};loadOutlineRenderingProperties=(e,t,i)=>{if(t.flag&ps.Material.Flag.EnabledToonEdge){void 0===as.prototype.getMmdOutlineRenderer&&i.warn('MMD Outline Renderer is not available. Please import "babylon-mmd/esm/Loader/mmdOutlineRenderer".'),e.renderOutline=!0,e.outlineWidth=t.edgeSize;const s=t.edgeColor;e.outlineColor=new L(s[0],s[1],s[2]),e.outlineAlpha=s[3]}};afterBuildSingleMaterial=()=>{}}class $r{lengthComputable;total;_onProgress;_unprocessedTasks;_processingTasks;_endedTaskNames;_endedTasksTotal;constructor(e,t,i){this.lengthComputable=e;let s=0;for(let e=0;e=i.cost&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=i.cost))}setTaskProgress(e,t){const i=this._getTaskState(e);return null!==i&&(i.progress=t,i.progress>=i.cost&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=i.cost),!0)}setTaskProgressRatio(e,t,i){const s=this._getTaskState(e);return null!==s&&(s.progress=i?Math.floor(s.cost*t):s.cost*t,s.progress>=s.cost&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=s.cost),!0)}endTask(e){const t=this._getTaskState(e);null!==t&&(this._processingTasks.delete(e),this._endedTaskNames.add(e),this._endedTasksTotal+=t.cost)}invokeProgressEvent(){null!==this._onProgress&&this._onProgress({lengthComputable:this.lengthComputable,loaded:this.loaded,total:this.total})}get loaded(){let e=this._endedTasksTotal;for(const[t,i]of this._processingTasks)e+=i.progress;return e}}class Jr{name;extensions;materialBuilder;useSdef;buildSkeleton;buildMorph;boundingBoxMargin;preserveSerializationData;_loggingEnabled;log;warn;error;static _SharedStandardMaterialBuilder=new Qr;constructor(e,t){this.name=e,this.extensions=t,this.materialBuilder=Jr._SharedStandardMaterialBuilder,this.useSdef=!0,this.buildSkeleton=!0,this.buildMorph=!0,this.boundingBoxMargin=10,this.preserveSerializationData=!1,this._loggingEnabled=!1,this.log=this._logDisabled,this.warn=this._warnDisabled,this.error=this._errorDisabled}importMeshAsync(e,t,i,s,r,n){return this._loadAsyncInternal(t,null,i,s,r)}loadAsync(e,t,i,s,r){return this._loadAsyncInternal(e,null,t,i,s).then((()=>{}))}loadAssetContainerAsync(e,t,i,s,r){const n=new ar(e);return this._loadAsyncInternal(e,n,t,i,s).then((()=>n))}async _loadAsyncInternal(e,t,i,s,r){const n=await this._parseFileAsync(i.arrayBuffer),a=new $r(!0,this._getProgressTaskCosts(i,n),r??null);a.endTask("Parse"),a.invokeProgressEvent(),e._blockEntityCollection=!!t;const o=new Zs(n.header.modelName,e);o._parentContainer=t,e._blockEntityCollection=!1,o.setEnabled(!1);const h=await this._buildGeometryAsync(i,n,o,e,t,a),l=i.preserveSerializationData?new Map:null,{materials:c,multiMaterials:d,textureLoadPromise:u}=await this._buildMaterialAsync(i,n,o,h.meshes,l,e,t,s,a),f=[];let _=null;i.buildSkeleton?_=await this._buildSkeletonAsync(i,n,h.meshes,e,t,f,a):a.endTask("Build Skeleton");const p=[];let g=null;if(i.buildMorph&&(g=await this._buildMorphAsync(i,n,h,e,t,p,a)),0!==i.boundingBoxMargin&&this._applyBoundingBoxMargin(h.meshes,i.boundingBoxMargin),o.metadata={isMmdModel:!0,header:{modelName:n.header.modelName,englishModelName:n.header.englishModelName,comment:n.header.comment,englishComment:n.header.englishComment},bones:f,morphs:p,rigidBodies:n.rigidBodies,joints:n.joints,meshes:h.meshes,materials:c,skeleton:_},i.preserveSerializationData){const e=[],t=n.materials;for(let i=0;i4,u=d?this.getVerticesData(G.MatricesIndicesExtraKind):null,f=d?this.getVerticesData(G.MatricesWeightsExtraKind):null,_=e.getTransformMatrices(this),p=M.Zero(),g=new y,m=new y,T=new y,x=new y,E=new S,v=new S,A=new M,b=i._sourcePositions,I=i._sourceNormals;let R,C=0;for(let e=0;e0&&(y.FromFloat32ArrayToRefScaled(_,Math.floor(16*l[C+R]),i,m),g.addToSelf(m));if(d)for(R=0;R<4;R++)i=f[C+R],i>0&&(y.FromFloat32ArrayToRefScaled(_,Math.floor(16*u[C+R]),i,m),g.addToSelf(m));M.TransformCoordinatesFromFloatsToRef(b[e],b[e+1],b[e+2],g,p),p.toArray(s,e),t&&(M.TransformNormalFromFloatsToRef(I[e],I[e+1],I[e+2],g,p),p.toArray(r,e)),g.reset()}else{const i=c[C+0],n=c[C+1];y.FromArrayToRef(_,Math.floor(16*l[C+0]),T),y.FromArrayToRef(_,Math.floor(16*l[C+1]),x),S.FromRotationMatrixToRef(T,E),S.FromRotationMatrixToRef(x,v),y.FromQuaternionToRef(S.SlerpToRef(E,v,n,E),m),M.TransformCoordinatesFromFloatsToRef(b[e]-a[e],b[e+1]-a[e+1],b[e+2]-a[e+2],m,A),M.TransformCoordinatesFromFloatsToRef(o[e],o[e+1],o[e+2],T,p).scaleAndAddToRef(i,A),M.TransformCoordinatesFromFloatsToRef(h[e],h[e+1],h[e+2],x,p).scaleAndAddToRef(n,A),A.toArray(s,e),t&&(M.TransformNormalFromFloatsToRef(I[e],I[e+1],I[e+2],m,A),A.toArray(r,e))}}return this.updateVerticesData(G.PositionKind,s),t&&this.updateVerticesData(G.NormalKind,r),this}}class sn extends Jr{referenceFiles;constructor(e,t){super(e,t),this.referenceFiles=[]}loadFile(e,t,i,s,r,n,a){const o=this.materialBuilder,h=this.useSdef,l=this.buildSkeleton,c=this.buildMorph,d=this.boundingBoxMargin,u=this.referenceFiles,f=this.preserveSerializationData;return e._loadFile(t,((e,i)=>{const r={arrayBuffer:e,pmFileId:t instanceof File?en.GetId(t).toString():t,materialBuilder:o,useSdef:h,buildSkeleton:l,buildMorph:c,boundingBoxMargin:d,referenceFiles:u,preserveSerializationData:f};s(r,i)}),r,!0,n,a)}_getProgressTaskCosts(e,t){const i=super._getProgressTaskCosts(e,t);if(i.push({name:"Build Geometry",cost:t.indices.length}),e.buildMorph){let e=0;const s=t.morphs;for(let t=0;t{l=e.materialBuilder.buildMaterials(i.uniqueId,t.materials,c,t.textures,o,"file:"+e.pmFileId+"_",e.referenceFiles,d,s,n,a,r,this,(e=>{e.lengthComputable&&(h.setTaskProgressRatio("Texture Load",e.loaded/e.total,!0),h.invokeProgressEvent())}),(()=>u()))})),f=Array.isArray(l)?l:await l;for(let e=0;ePromise.reject(e)))}});class rn{_vertexIndexSize;_textureIndexSize;_materialIndexSize;_boneIndexSize;_morphIndexSize;_rigidBodyIndexSize;constructor(e,t,i,s,r,n){this._vertexIndexSize=e,this._textureIndexSize=t,this._materialIndexSize=i,this._boneIndexSize=s,this._morphIndexSize=r,this._rigidBodyIndexSize=n}getVertexIndex(e){switch(this._vertexIndexSize){case 1:return e.getUint8();case 2:return e.getUint16();case 4:return e.getInt32();default:throw new Error(`Invalid vertexIndexSize: ${this._vertexIndexSize}`)}}_getNonVertexIndex(e,t){switch(t){case 1:return e.getInt8();case 2:return e.getInt16();case 4:return e.getInt32();default:throw new Error(`Invalid indexSize: ${t}`)}}getTextureIndex(e){return this._getNonVertexIndex(e,this._textureIndexSize)}getMaterialIndex(e){return this._getNonVertexIndex(e,this._materialIndexSize)}getBoneIndex(e){return this._getNonVertexIndex(e,this._boneIndexSize)}getMorphIndex(e){return this._getNonVertexIndex(e,this._morphIndexSize)}getRigidBodyIndex(e){return this._getNonVertexIndex(e,this._rigidBodyIndexSize)}}class nn{constructor(){}static async ParseAsync(e,t=new xs){const i=new Es(e),s=this._ParseHeader(i,t),r=new rn(s.vertexIndexSize,s.textureIndexSize,s.materialIndexSize,s.boneIndexSize,s.morphIndexSize,s.rigidBodyIndexSize),n=await this._ParseVerticesAsync(i,r,s),a=this._ParseIndices(i,r,s),o=this._ParseTextures(i),h=this._ParseMaterials(i,r),l=this._ParseBones(i,r),c=this._ParseMorphs(i,r),d=this._ParseDisplayFrames(i,r),u=this._ParseRigidBodies(i,r),f=this._ParseJoints(i,r),_=s.version<=2?[]:this._ParseSoftBodies(i,r,s);return i.bytesAvailable>0&&t.warn(`There are ${i.bytesAvailable} bytes left after parsing`),{header:s,vertices:n,indices:a,textures:o,materials:h,bones:l,morphs:c,displayFrames:d,rigidBodies:u,joints:f,softBodies:_}}static _ParseHeader(e,t){if(e.bytesAvailable<17)throw new RangeError("is not pmx file");const i=e.getSignatureString(3);if("PMX"!==i)throw new RangeError("is not pmx file");e.getInt8();const s=e.getFloat32(),r=e.getUint8(),n=e.getUint8();e.initializeTextDecoder(n===ps.Header.Encoding.Utf8?"utf-8":"utf-16le");const a=e.getUint8(),o=e.getUint8(),h=e.getUint8(),l=e.getUint8(),c=e.getUint8(),d=e.getUint8(),u=e.getUint8();if(r<8)throw new Error(`Invalid globalsCount: ${r}`);if(8setTimeout(e,0))),n=performance.now())}return r}static _ParseIndices(e,t,i){const s=e.getInt32(),r=new ArrayBuffer(s*i.vertexIndexSize);let n;switch(i.vertexIndexSize){case 1:n=new Uint8Array(r);break;case 2:n=new Uint16Array(r);break;case 4:n=new Int32Array(r);break;default:throw new Error(`Invalid vertexIndexSize: ${i.vertexIndexSize}`)}for(let i=0;iPromise.reject(e)))}});class an{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((e=>{e.type!==Ui.POINTERDOWN?e.type===Ui.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=_e.j.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??_e.j.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}on.EASINGMODE_EASEIN=0,on.EASINGMODE_EASEOUT=1,on.EASINGMODE_EASEINOUT=2;class hn{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((e=>{if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):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}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(hn.EasingFunction.setEasingMode(hn.EasingMode),this._radiusBounceTransition=mr.CreateAnimation("radius",mr.ANIMATIONTYPE_FLOAT,60,hn.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=mr.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()}}hn.EasingFunction=new class extends on{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)}}(.3),hn.EasingMode=on.EASINGMODE_EASEOUT;class ln{constructor(){this.onTargetFramingAnimationEndObservable=new se.cP,this._mode=ln.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();ln.EasingFunction.setEasingMode(ln.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==Ui.POINTERDOWN?e.type===Ui.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,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 M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new M(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),h&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===ln.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=_e.j.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=mr.CreateAnimation("beta",mr.ANIMATIONTYPE_FLOAT,60,ln.EasingFunction));const e=mr.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=_e.j.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&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}ln.EasingFunction=new class extends on{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)}},ln.EasingMode=on.EASINGMODE_EASEINOUT,ln.IgnoreBoundsSizeMode=0,ln.FitFrustumSidesMode=1,ce.AddNodeConstructor("TargetCamera",((e,t)=>()=>new cn(e,M.Zero(),t)));class cn extends ni{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=M.Zero(),this._tmpTargetVector=M.Zero(),this.cameraDirection=new M(0,0,0),this.cameraRotation=new A(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new S,this.rotation=new M(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=M.Zero(),this._initialFocalDistance=1,this._viewMatrix=y.Zero(),this._camMatrix=y.Zero(),this._cameraTransformMatrix=y.Zero(),this._cameraRotationMatrix=y.Zero(),this._referencePoint=new M(0,0,1),this._transformedReferencePoint=M.Zero(),this._deferredPositionUpdate=new M,this._deferredRotationQuaternionUpdate=new S,this._deferredRotationUpdate=new M,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=M.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)}_initCache(){super._initCache(),this._cache.lockedTarget=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new M(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new S(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()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=a),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),y.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&&S.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)return this.parent.getWorldMatrix().invertToRef(R.Matrix[0]),M.TransformNormalToRef(this.cameraDirection,R.Matrix[0],R.Vector3[0]),this._deferredPositionUpdate.addInPlace(R.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));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;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(S.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();this.attached[t]?k.V.Warn("camera input of type "+t+" already exists on camera"):(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)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}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=!ni.ForceAttachControlToAlwaysPreventDefault&&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 e in this.attached){const i=this.attached[e],s=he.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=dn[e];if(i){const s=t[e],r=he.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=dn[this.attached[t].getClassName()];if(i){const s=he.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class fn{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Xe.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const a=n.event,o="touch"===a.pointerType;if(n.type!==Ui.POINTERMOVE&&-1===this.buttons.indexOf(a.button))return;const h=a.target;if(this._altKey=a.altKey,this._ctrlKey=a.ctrlKey,this._metaKey=a.metaKey,this._shiftKey=a.shiftKey,this._buttonsPressed=a.buttons,t.isPointerLock){const e=a.movementX,t=a.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==Ui.POINTERDOWN&&n.type!==Ui.POINTERDOUBLETAP&&o&&this._pointA?.pointerId!==a.pointerId&&this._pointB?.pointerId!==a.pointerId)return;if(n.type!==Ui.POINTERDOWN||-1!==this._currentActiveButton&&!o)if(n.type===Ui.POINTERDOUBLETAP)this.onDoubleTap(a.pointerType);else if(n.type!==Ui.POINTERUP||this._currentActiveButton!==a.button&&!o){if(n.type===Ui.POINTERMOVE)if(e||a.preventDefault(),this._pointA&&null===this._pointB){const e=a.clientX-this._pointA.x,t=a.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=a.clientX,this._pointA.y=a.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===a.pointerId?this._pointA:this._pointB;e.x=a.clientX,e.y=a.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,o=t*t+i*i,h={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:a.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,o,r,h),r=h,s=o}}else{try{h?.releasePointerCapture(a.pointerId)}catch(e){}o||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==a.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==a.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(a),e||a.preventDefault()}else{try{h?.setPointerCapture(a.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType};else{if(null!==this._pointB)return;this._pointB={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType}}-1!==this._currentActiveButton||o||(this._currentActiveButton=a.button),this.onButtonDown(a),e||(a.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Ui.POINTERDOWN|Ui.POINTERUP|Ui.POINTERMOVE|Ui.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Xe.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Xe.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}z([q()],fn.prototype,"buttons",void 0);class _n extends fn{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(0!==this.panningSensibility&&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||_n.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(t-e)*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(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,r,n){0===i&&null===r||0===s&&null===n||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,s),this._computeMultiTouchPanning(r,n)):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(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}_n.MinimumRadiusForPinch=.001,z([q()],_n.prototype,"buttons",void 0),z([q()],_n.prototype,"angularSensibilityX",void 0),z([q()],_n.prototype,"angularSensibilityY",void 0),z([q()],_n.prototype,"pinchPrecision",void 0),z([q()],_n.prototype,"pinchDeltaPercentage",void 0),z([q()],_n.prototype,"useNaturalPinchZoom",void 0),z([q()],_n.prototype,"pinchZoom",void 0),z([q()],_n.prototype,"panningSensibility",void 0),z([q()],_n.prototype,"multiTouchPanning",void 0),z([q()],_n.prototype,"multiTouchPanAndZoom",void 0),dn.ArcRotateCameraPointersInput=_n;class pn{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=Xe.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===Wi.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,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?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Xe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==Ui.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===Ki.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=P.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);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,Ui.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=et.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,y.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=M.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=R.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)()=>new Tn(e,0,0,1,M.Zero(),t)));class Tn extends cn{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 y,this._upToYMatrix=new y,this._upVector=M.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){y.RotationAlignToRef(M.UpReadOnly,this._upVector,this._yToUpMatrix),y.RotationAlignToRef(this._upVector,M.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}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}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 null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new hn,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new ln,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new an,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,a=!0){super(e,M.Zero(),n,a),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=M.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=A.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new y,this.panningAxis=new M(1,1,0),this._transformedDirection=new M,this.mapPanning=!1,this.onMeshTargetChangedObservable=new se.cP,this.checkCollisions=!1,this.collisionRadius=new M(.5,.5,.5),this._previousPosition=M.Zero(),this._collisionVelocity=M.Zero(),this._newPosition=M.Zero(),this._computationVector=M.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let a=Math.sin(this.beta);0===a&&(a=1e-4);const o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*a,this.radius*n,this.radius*r*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let h=this.upVector;this.allowUpsideDown&&this.beta<0&&(h=h.clone(),h=h.negate()),this._computeViewMatrix(this._position,o,h),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=M.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new mn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new M(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=A.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 e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_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)}attachControl(e,t,i=!0,s=2){const r=arguments;t=Xe.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||M.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?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+=2*t*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){if(s=this.overrideCloneAlphaBetaRadius??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 t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,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);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||M.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Zs.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(void 0===e.min){const t=e||this.getScene().meshes;i=Zs.MinMax(t),s=M.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=Zs.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ni.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ni.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ni.RIG_MODE_STEREOSCOPIC_INTERLACED:case ni.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new Tn(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 ni.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ni.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ni.RIG_MODE_STEREOSCOPIC_INTERLACED:case ni.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ni.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=M.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),a=n*r,o=.5*s*i,h=o*Math.sqrt(1+1/(a*a)),l=o*Math.sqrt(1+1/(n*n));return Math.max(h,l)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}z([q()],Tn.prototype,"alpha",void 0),z([q()],Tn.prototype,"beta",void 0),z([q()],Tn.prototype,"radius",void 0),z([q()],Tn.prototype,"overrideCloneAlphaBetaRadius",void 0),z([J("target")],Tn.prototype,"_target",void 0),z([ee("targetHost")],Tn.prototype,"_targetHost",void 0),z([q()],Tn.prototype,"inertialAlphaOffset",void 0),z([q()],Tn.prototype,"inertialBetaOffset",void 0),z([q()],Tn.prototype,"inertialRadiusOffset",void 0),z([q()],Tn.prototype,"lowerAlphaLimit",void 0),z([q()],Tn.prototype,"upperAlphaLimit",void 0),z([q()],Tn.prototype,"lowerBetaLimit",void 0),z([q()],Tn.prototype,"upperBetaLimit",void 0),z([q()],Tn.prototype,"lowerRadiusLimit",void 0),z([q()],Tn.prototype,"upperRadiusLimit",void 0),z([q()],Tn.prototype,"inertialPanningX",void 0),z([q()],Tn.prototype,"inertialPanningY",void 0),z([q()],Tn.prototype,"pinchToPanMaxDistance",void 0),z([q()],Tn.prototype,"panningDistanceLimit",void 0),z([J()],Tn.prototype,"panningOriginTarget",void 0),z([q()],Tn.prototype,"panningInertia",void 0),z([q()],Tn.prototype,"zoomToMouseLocation",null),z([q()],Tn.prototype,"zoomOnFactor",void 0),z([$()],Tn.prototype,"targetScreenOffset",void 0),z([q()],Tn.prototype,"allowUpsideDown",void 0),z([q()],Tn.prototype,"useInputToRestoreState",void 0),d("BABYLON.ArcRotateCamera",Tn);class xn extends Ze{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=y.Identity(),this._projectionMatrix=y.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=M.Zero()),M.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=M.Zero()),M.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}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=M.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=M.Cross(this.direction,Os.Y),t=M.Cross(e,this.direction);return M.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=M.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=y.Identity()),y.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 void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?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=R.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),M.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(M.Dot(t,M.Up()))&&(t.z=1e-13);const s=R.Vector3[1];return i.addToRef(t,s),y.LookAtLHToRef(i,s,M.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}z([J()],xn.prototype,"position",null),z([J()],xn.prototype,"direction",null),z([q()],xn.prototype,"shadowMinZ",null),z([q()],xn.prototype,"shadowMaxZ",null),ce.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new En(e,M.Zero(),t)));class En extends xn{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Ze.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&y.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=M.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;y.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?o:a,h?a:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}z([q()],En.prototype,"shadowFrustumSize",null),z([q()],En.prototype,"shadowOrthoScale",null),z([q()],En.prototype,"autoUpdateExtends",void 0),z([q()],En.prototype,"autoCalcShadowZBounds",void 0),z([q("orthoLeft")],En.prototype,"_orthoLeft",void 0),z([q("orthoRight")],En.prototype,"_orthoRight",void 0),z([q("orthoTop")],En.prototype,"_orthoTop",void 0),z([q("orthoBottom")],En.prototype,"_orthoBottom",void 0),d("BABYLON.DirectionalLight",En),ce.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new vn(e,M.Zero(),t)));class vn extends Ze{constructor(e,t,i){super(e,i),this.groundColor=new L(0,0,0),this.direction=t||M.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=M.Normalize(e.subtract(M.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=M.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=M.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=y.Identity()),this._worldMatrix}getTypeID(){return Ze.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}z([Z()],vn.prototype,"groundColor",void 0),z([J()],vn.prototype,"direction",void 0),d("BABYLON.HemisphericLight",vn),Zs._GroundMeshParser=(e,t)=>An.Parse(e,t);class An extends Zs{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);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=R.Matrix[5];i.invertToRef(s);const r=R.Vector3[8];if(M.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return M.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new M(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=R.Matrix[5];s.invertToRef(r);const n=R.Vector3[8];if(M.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return M.TransformNormalFromFloatsToRef(a.x,a.y,a.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){c=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new M(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),d=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[d]/255,f=e.buffer[d+1]/255,_=e.buffer[d+2]/255;const p=e.buffer[d+3]/255;c&&(u=1-u,f=1-f,_=1-_);const g=u*h.r+f*h.g+_*h.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*g:e.minHeight-a,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,d=i[3*a+1]>=e.minHeight;l&&c&&d&&(t.push(s),t.push(r),t.push(a)),i[3*h+1]>=e.minHeight&&l&&d&&(t.push(h),t.push(s),t.push(a))}Ps.ComputeNormals(i,t,s);const d=new Ps;return d.indices=t,d.positions=i,d.normals=s,d.uvs=r,d}function yn(e,t={},i){const s=new An(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Mn(t).applyToMesh(s,t.updatable),s._setReady(!0),s}Ps.CreateGround=Mn,Ps.CreateTiledGround=bn,Ps.CreateGroundFromHeightMap=Sn,Zs.CreateGround=(e,t,i,s,r,n)=>yn(e,{width:t,height:i,subdivisions:s,updatable:n},r),Zs.CreateTiledGround=(e,t,i,s,r,n,a,o,h)=>function(e,t,i=null){const s=new Zs(e,i);return bn(t).applyToMesh(s,t.updatable),s}(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:a,updatable:h},o),Zs.CreateGroundFromHeightMap=(e,t,i,s,r,n,a,o,h,l,c)=>function(e,t,i={},s=null){const r=i.width||10,n=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,h=i.maxHeight||1,l=i.colorFilter||new L(.3,.59,.11),c=i.alphaFilter||0,d=i.updatable,u=i.onReady;s=s||_.q.LastCreatedScene;const f=new An(e,s);let p;f._subdivisionsX=a,f._subdivisionsY=a,f._width=r,f._height=n,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((a+1)*(a+1)));const g=(e,t,i)=>{Sn({width:r,height:n,subdivisions:a,minHeight:o,maxHeight:h,colorFilter:l,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(f,d),u&&u(f,p),f._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);g(r,t,i)};Xe.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else g(t.data,t.width,t.height);return f}(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:a,updatable:h,onReady:l,alphaFilter:c},o);gt.l.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class In{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const a=e.getMaterial();if(!a)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return a.isReadyForSubMesh(e.getMesh(),e,t);const o=[],h=[G.PositionKind];let l=!1,c=!1;if(a){const e=a.needAlphaTesting(),t=a.getAlphaTestTexture(),i=t&&t.hasAlpha&&(a.useAlphaFromDiffuseTexture||a._useAlphaFromAlbedoTexture);t&&(e||i)&&(o.push("#define DIFFUSE"),r.isVerticesDataPresent(G.UV2Kind)&&1===t.coordinatesIndex?(o.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(G.UVKind)&&(o.push("#define DIFFUSEUV1"),l=!0),e&&(o.push("#define ALPHATEST"),o.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||o.push("#define DIFFUSE_ISLINEAR"));const s=a.opacityTexture;s&&(o.push("#define OPACITY"),r.isVerticesDataPresent(G.UV2Kind)&&1===s.coordinatesIndex?(o.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(G.UVKind)&&(o.push("#define OPACITYUV1"),l=!0))}i&&(o.push("#define EMISSIVE"),r.isVerticesDataPresent(G.UV2Kind)&&1===i.coordinatesIndex?(o.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(G.UVKind)&&(o.push("#define EMISSIVEUV1"),l=!0),i.gammaSpace||o.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(G.ColorKind)&&r.hasVertexAlpha&&a.transparencyMode!==Ws.MATERIAL_OPAQUE&&(h.push(G.ColorKind),o.push("#define VERTEXALPHA")),l&&(h.push(G.UVKind),o.push("#define UV1")),c&&(h.push(G.UV2Kind),o.push("#define UV2"));const d=new Ct;if(r.useBones&&r.computeBonesUsingShaders){h.push(G.MatricesIndicesKind),h.push(G.MatricesWeightsKind),r.numBoneInfluencers>4&&(h.push(G.MatricesIndicesExtraKind),h.push(G.MatricesWeightsExtraKind)),o.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?o.push("#define BONETEXTURE"):o.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,r)}else o.push("#define NUM_BONE_INFLUENCERS 0");const u=r.morphTargetManager;let f=0;u&&(f=u.numMaxInfluencers||u.numInfluencers,f>0&&(o.push("#define MORPHTARGETS"),o.push("#define NUM_MORPH_INFLUENCERS "+f),u.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),Ut(h,r,f))),t&&(o.push("#define INSTANCES"),Vt(h),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),Dt(a,this._scene,o),this._addCustomEffectDefines(o);const _=e._getDrawWrapper(void 0,!0),p=_.defines,g=o.join("\n");if(p!==g){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Pt(e),_.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:f}),g)}return _.effect.isReady()}render(){for(let e=0;el.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[G.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 Xe.Instantiate(e.customType).Parse(e,t,i)}}In._SceneComponentInitialization=e=>{throw(0,re.n)("EffectLayerSceneComponent")},z([q()],In.prototype,"name",void 0),z([te()],In.prototype,"neutralColor",void 0),z([q()],In.prototype,"isEnabled",void 0),z([K(11,void 0)],In.prototype,"camera",null),z([q()],In.prototype,"renderingGroupId",null),z([q()],In.prototype,"disableBoundingBoxesFromEffectLayer",void 0);gt.l.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";gt.l.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;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;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",mi.AddParser(pi.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===ni.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==ni.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(pi.NAME_EFFECTLAYER);t||(t=new Rn(e),e._addComponent(t))},mi.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new Rt("GlowLayerVBP1",new A(0,1),n,{width:e,height:t},null,st.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Rt("GlowLayerHBP2",new A(1,0),n,{width:s,height:r},null,st.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new Rt("GlowLayerVBP2",new A(0,1),n,{width:s,height:r},null,st.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Ws.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=he.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Cn(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return he.Parse((()=>new Pn(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}z([q()],Pn.prototype,"colorAmount",void 0),z([q()],Pn.prototype,"edgeAmount",void 0),d("BABYLON.SharpenPostProcess",Pn);gt.l.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class Dn extends It{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=_.q.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new Ii}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,a=0,o){super(e,"imageProcessing",[],[],t,i,s,r,n,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];Ii&&(Ii.PrepareSamplers(t,this._defines),Ii.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}z([q()],Dn.prototype,"_fromLinearSpace",void 0);gt.l.ShadersStore.chromaticAberrationPixelShader="uniform sampler2D textureSampler; \nuniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}";class On extends It{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,s,r,n,a,o,h=0,l=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],s,r,n,a,o,null,h,void 0,null,l),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new A(.707,.707),this.centerPosition=new A(.5,.5),this.screenWidth=t,this.screenHeight=i,this.onApplyObservable.add((e=>{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return he.Parse((()=>new On(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}z([q()],On.prototype,"aberrationAmount",void 0),z([q()],On.prototype,"radialIntensity",void 0),z([q()],On.prototype,"direction",void 0),z([q()],On.prototype,"centerPosition",void 0),z([q()],On.prototype,"screenWidth",void 0),z([q()],On.prototype,"screenHeight",void 0),d("BABYLON.ChromaticAberrationPostProcess",On);gt.l.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class Fn extends It{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,a=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,a,void 0,null,o),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return he.Parse((()=>new Fn(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}z([q()],Fn.prototype,"intensity",void 0),z([q()],Fn.prototype,"animated",void 0),d("BABYLON.GrainPostProcess",Fn);gt.l.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_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 he.Parse((()=>new wn(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}d("BABYLON.FxaaPostProcess",wn);class Ln{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Xe.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Xe.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Xe.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}z([q()],Ln.prototype,"_name",void 0);class Nn{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=Xe.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Xe.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}gt.l.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class Bn extends It{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,a,o=0,h=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,a,null,o,void 0,null,h),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void k.V.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}z([q()],Bn.prototype,"lensSize",void 0),z([q()],Bn.prototype,"fStop",void 0),z([q()],Bn.prototype,"focusDistance",void 0),z([q()],Bn.prototype,"focalLength",void 0),d("BABYLON.CircleOfConfusionPostProcess",Bn);class Un extends Rt{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,a,o=null,h=st.BILINEAR_SAMPLINGMODE,l,c,d=0,u=!1,f=5){super(e,i,s,r,n,2,l,c,d,"#define DOF 1\n",u,f),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add((e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)}))}}z([q()],Un.prototype,"direction",void 0),d("BABYLON.DepthOfFieldBlurPostProcess",Un);gt.l.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class kn extends It{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,a,o,h,l=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,a,o,h,null,l,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var Vn;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(Vn||(Vn={}));class Gn extends Nn{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=Vn.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),a=n.isWebGPU||n.version>1?6:5;this._circleOfConfusion=new Bn("circleOfConfusion",t,1,null,st.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,h=15;switch(i){case Vn.High:o=3,h=51;break;case Vn.Medium:o=2,h=31;break;default:h=15,o=1}const l=h/Math.pow(2,o-1);let c=1;for(let t=0;t\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class zn extends It{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,a,o=0,h=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,a,null,o,void 0,null,h),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,n)),e.setFloat("exposure",this._exposure)}))}}z([q()],zn.prototype,"threshold",void 0),d("BABYLON.ExtractHighlightsPostProcess",zn);gt.l.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class Wn extends It{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,a,o,h,l=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,a,o,h,null,l,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}z([q()],Wn.prototype,"weight",void 0),d("BABYLON.BloomMergePostProcess",Wn);class Xn extends Nn{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new zn("highlights",1,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new Rt("horizontal blur",new A(1,0),10,t,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Rt("vertical blur",new A(0,1),10,t,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new Wn("bloomMerge",this._downscale,this._blurY,i,t,null,st.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;tthis.sharpen),!0),this.depthOfField=new Gn(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add((()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new Xn(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new On("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,st.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new Nn(a,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new Fn("Grain",1,null,st.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new Nn(a,this.GrainPostProcessId,(()=>this.grain),!0);let o=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,o?Xe.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new Dn("imageProcessing",1,null,st.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new Nn(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new wn("fxaa",1,null,st.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new Nn(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&k.V.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew Yn(e._name,e._name._hdr,t)),e,t,i)}}var qn,jn,Zn;z([q()],Yn.prototype,"sharpenEnabled",null),z([q()],Yn.prototype,"bloomKernel",null),z([q()],Yn.prototype,"_bloomWeight",void 0),z([q()],Yn.prototype,"_bloomThreshold",void 0),z([q()],Yn.prototype,"_hdr",void 0),z([q()],Yn.prototype,"bloomWeight",null),z([q()],Yn.prototype,"bloomThreshold",null),z([q()],Yn.prototype,"bloomScale",null),z([q()],Yn.prototype,"bloomEnabled",null),z([q()],Yn.prototype,"depthOfFieldEnabled",null),z([q()],Yn.prototype,"depthOfFieldBlurLevel",null),z([q()],Yn.prototype,"fxaaEnabled",null),z([q()],Yn.prototype,"samples",null),z([q()],Yn.prototype,"imageProcessingEnabled",null),z([q()],Yn.prototype,"glowLayerEnabled",null),z([q()],Yn.prototype,"chromaticAberrationEnabled",null),z([q()],Yn.prototype,"grainEnabled",null),d("BABYLON.DefaultRenderingPipeline",Yn),function(e){e.isMmdMesh=function(e){return!(null===e.metadata||!e.metadata.isMmdModel)},e.isMmdSkinnedMesh=function(e){return!(null===e.metadata||!e.metadata.isMmdModel)&&null!==e.metadata.skeleton}}(qn||(qn={})),function(e){e.isSerializationMetadata=function(e){return!0===e.containsSerializationData}}(jn||(jn={}));class Qn{_dataView;_encoder;_offset;constructor(e){this._dataView=new DataView(e),this._encoder=new TextEncoder,this._offset=0}get offset(){return this._offset}set offset(e){this._offset=e}setUint8(e){this._dataView.setUint8(this._offset,e),this._offset+=1}setUint8Array(e){const t=this._dataView;for(let i=0;i0;){const e=t.pop(),i=r.get(e),s=e.children;for(let e=0;e{const t=e.children;for(let s=0;s{const i=s.get(e);if(void 0!==i)for(let e=0;ee.texture===v)):-1,M=l.sphereTexture,b=M?g.findIndex((e=>e.texture===M)):-1,S=l.sphereTextureBlendMode??ps.Material.SphereTextureMode.Off,y=l.toonTexture,I=!!y&&y.name.startsWith("file:shared_toon_texture_")&&y.name.length<=27&&!isNaN(Number(y.name.substring(25)));let R;R=I?Number(y.name.substring(25))-1:y?g.findIndex((e=>e.texture===y)):-1;const C={name:i,englishName:a,diffuse:h,specular:c,shininess:u,ambient:f,evaluatedTransparency:_,flag:p,edgeColor:x,edgeSize:E,textureIndex:A,sphereTextureIndex:b,sphereTextureMode:S,isSharedToonTexture:I,toonTextureIndex:R,comment:e?.comment??"",linkedMaterial:l};m.push(C)}}}}const x=new Array(a.morphs.length).fill(null);for(let e=0;ee.linkedMaterial===r));M.setInt32(n),M.setUint32(s.verticesStart),M.setUint32(s.verticesCount),M.setUint32(s.indexStart),M.setUint32(s.indexCount)}}else{const e=t.material,i=m.findIndex((t=>t.linkedMaterial===e));M.setInt32(i)}const r=i.getVerticesData(G.PositionKind),n=r.length/3;M.setUint32(n),M.setFloat32Array(r);let a=i.getVerticesData(G.NormalKind);if(a.length!==3*n){this.warn(`mesh ${t.name} normals vertex count is different from positions vertex count`);const e=new Float32Array(3*n);e.set(a),a=e}M.setFloat32Array(a);let o=i.getVerticesData(G.UVKind);if(o.length!==2*n){this.warn(`mesh ${t.name} uv vertex count is different from positions vertex count`);const e=new Float32Array(2*n);e.set(o),o=e}M.setFloat32Array(o);const l=[];{const e=i.getVerticesData(os.AdditionalUV1Kind);null!==e&&l.push(e);const t=i.getVerticesData(os.AdditionalUV2Kind);null!==t&&l.push(t);const s=i.getVerticesData(os.AdditionalUV3Kind);null!==s&&l.push(s);const r=i.getVerticesData(os.AdditionalUV4Kind);null!==r&&l.push(r)}M.setUint8(l.length);for(let e=0;e0;){const s=r.pop(),n=s.getParent();if(n?s.getLocalMatrix().multiplyToRef(n.getFinalMatrix(),s.getFinalMatrix()):t?s.getLocalMatrix().multiplyToRef(t,s.getFinalMatrix()):s.getFinalMatrix().copyFrom(s.getLocalMatrix()),-1!==s._index){const t=null===s._index?i:s._index;s.getAbsoluteInverseBindMatrix().multiplyToArray(s.getFinalMatrix(),e,16*t)}const a=s.getChildren();for(const e of a)r.push(e)}}}this._identity.copyToArray(e,16*this.bones.length)}}}async function ea(e,t=""){const i=[];for(let s=0;s{e.readEntries(t,i)}));i.push(...await ea(s,t+r.name+"/"))}else i.push(r)}return i}class ta{async build(e,t){cs.OverrideEngineCreateEffect(t);const i=Ts.GetPluginForExtension(".pmd");i.loggingEnabled=!0,i.preserveSerializationData=!0;const s=Ts.GetPluginForExtension(".pmx");s.loggingEnabled=!0,s.preserveSerializationData=!0;const r=s.materialBuilder;r.deleteTextureBufferAfterLoad=!1,r.renderMethod=qr.AlphaEvaluation;const n=new as(t);n.ambientColor=new L(.5,.5,.5);const a=new Tn("camera",0,0,45,new M(0,10,0),n);a.maxZ=5e3,a.fov=Math.PI/180*30,a.speed=.5,a.setPosition(new M(0,10,-45)),a.attachControl(e,!0);const o=new vn("hemisphericLight",new M(0,1,0),n);o.intensity=.5,o.specular=new L(0,0,0),o.groundColor=new L(1,1,1);const h=new En("directionalLight",new M(.5,-1,1),n);h.intensity=.5,h.autoCalcShadowZBounds=!1,h.autoUpdateExtends=!1,h.shadowMaxZ=60,h.shadowMinZ=-30,h.orthoTop=54,h.orthoBottom=-3,h.orthoLeft=-30,h.orthoRight=30,h.shadowOrthoScale=0;const l=new Zt(1024,h,!0,a);l.transparencyShadow=!0,l.usePercentageCloserFiltering=!0,l.forceBackFacesOnly=!1,l.bias=.01,l.filteringQuality=Zt.QUALITY_MEDIUM,l.frustumEdgeFalloff=.1,yn("ground1",{width:100,height:100,subdivisions:2,updatable:!1},n).receiveShadows=!0;const c=new Yn("default",!0,n);c.samples=4,c.fxaaEnabled=!0,c.imageProcessingEnabled=!1;const d=new Zr(n),u=async e=>{if(T)return;if(null!==_){for(const e of _.metadata.meshes)l.removeShadowCaster(e);_.dispose(!1,!0),_=null}T=!0,t.displayLoadingUI();const i=e.webkitRelativePath;D.textContent=e.name,_=await Ts.ImportMeshAsync(void 0,i.substring(0,i.lastIndexOf("/")+1),e,n,(i=>t.loadingUIText=`


Loading (${e.name})... ${i.loaded}/${i.total} (${Math.floor(100*i.loaded/i.total)}%)`)).then((e=>{const t=e.meshes[0];return Jn.OverrideComputeTransformMatrices(t.metadata.skeleton),t.metadata.skeleton?._markAsDirty(),t}));{const e=_.metadata.meshes;for(let t=0;te.material===s));for(const e of t)if(await d.hasFragmentsOnlyOpaqueOnGeometry(r,e,null)){p[i]=!1;break}}else p[i]=!1;g[i]=s.transparencyMode??-1}}X(),t.hideLoadingUI(),setTimeout((()=>T=!1),1500)};let f=null,_=null;const p=[],g=[];let m="Alpha Mode",T=!1;const x=e=>{if(null===_)return;const t=_.metadata.materials;if("Alpha Mode"===e)for(let e=0;e{C.style.backgroundColor="#444444",P.style.backgroundColor="#111111",B.style.display="block",O.style.display="block",F.style.display="block",U.style.display="none",G.style.display="none",z.style.display="none"},R.appendChild(C);const P=document.createElement("div");P.textContent="Fix Material",P.style.width="100%",P.style.height="auto",P.style.border="none",P.style.backgroundColor="#111111",P.style.fontSize="20px",P.style.textAlign="center",P.style.color="white",P.style.cursor="pointer",P.onclick=()=>{C.style.backgroundColor="#111111",P.style.backgroundColor="#444444",B.style.display="none",O.style.display="none",F.style.display="none",U.style.display="flex",G.style.display="block",z.style.display="block"},R.appendChild(P);const D=document.createElement("div");D.textContent="No PMX file selected",D.style.width="350px",D.style.height="auto",D.style.fontSize="18px",D.style.marginBottom="10px",D.style.border="1px solid black",D.style.boxSizing="border-box",D.style.padding="10px",D.style.overflow="scroll",b.appendChild(D);const O=document.createElement("div");O.textContent="Files",O.style.width="100%",O.style.height="auto",O.style.fontSize="18px",O.style.backgroundColor="#444444",O.style.color="white",O.style.padding="2px 5px",O.style.boxSizing="border-box",b.appendChild(O);const F=document.createElement("div");F.style.width="350px",F.style.flexGrow="1",F.style.overflow="auto",F.style.marginBottom="10px",F.style.border="1px solid black",F.style.boxSizing="border-box",b.appendChild(F);const w=document.createElement("ul");w.style.height="auto",w.style.fontSize="16px",F.appendChild(w);const N=()=>{w.innerHTML="";for(const e of y){const t=document.createElement("li");t.style.whiteSpace="nowrap";const i=e.webkitRelativePath;t.textContent=i.substring(i.indexOf("/")+1),(e.name.endsWith(".pmx")||e.name.endsWith(".pmd"))&&(t.style.color="blue",t.style.cursor="pointer",t.style.textDecoration="underline",t.onclick=()=>{f=e,u(e)}),w.appendChild(t)}},B=document.createElement("input");B.style.width="100%",B.style.minHeight="80px",B.style.display="block",B.style.backgroundColor="black",B.style.color="white",B.style.marginBottom="10px",B.style.fontSize="20px",B.type="file",B.setAttribute("directory",""),B.setAttribute("webkitdirectory",""),B.setAttribute("allowdirs",""),B.ondragover=e=>{e.preventDefault()},B.ondrop=async e=>{e.preventDefault();const t=e.dataTransfer.items;if(!t)return;const r=[];for(let e=0;e{s.file(e,t)}));""===r.webkitRelativePath&&(Object.defineProperty(r,"webkitRelativePath",{writable:!0}),r.webkitRelativePath=s.fullPath),t.push(r)}return t}(n),N(),s.referenceFiles=y,i.referenceFiles=y},B.onchange=()=>{null!==B.files&&(y=Array.from(B.files),N(),s.referenceFiles=y,i.referenceFiles=y)},b.appendChild(B);const U=document.createElement("div");U.style.width="100%",U.style.height="auto",U.style.display="flex",U.style.flexDirection="row",U.style.justifyContent="space-between",b.appendChild(U);const k=document.createElement("button");k.textContent="Alpha Mode",k.style.flexGrow="1",k.style.height="auto",k.style.border="none",k.style.fontSize="16px",k.style.backgroundColor="#444444",k.style.color="white",k.style.cursor="pointer",k.onclick=()=>{"Alpha Mode"!==m&&(k.style.backgroundColor="#444444",V.style.backgroundColor="#111111",m="Alpha Mode",x(m),X())},U.appendChild(k);const V=document.createElement("button");V.textContent="Force Depth Write Mode",V.style.flexGrow="1",V.style.height="auto",V.style.border="none",V.style.fontSize="16px",V.style.backgroundColor="#111111",V.style.color="white",V.style.cursor="pointer",V.onclick=()=>{"Force Depth Write Mode"!==m&&(k.style.backgroundColor="#111111",V.style.backgroundColor="#444444",m="Force Depth Write Mode",x(m),X())},U.appendChild(V);const G=document.createElement("div");G.textContent="Materials",G.style.width="100%",G.style.height="auto",G.style.fontSize="18px",G.style.backgroundColor="#444444",G.style.color="white",G.style.padding="2px 5px",G.style.boxSizing="border-box",b.appendChild(G);const z=document.createElement("div");z.style.width="350px",z.style.flexGrow="1",z.style.overflow="auto",z.style.marginBottom="10px",z.style.border="1px solid black",z.style.boxSizing="border-box",b.appendChild(z);const W=document.createElement("ol");W.start=0,W.style.height="auto",W.style.fontSize="16px",z.appendChild(W);const X=()=>{if(W.innerHTML="",null===_)return;const e=_.metadata.meshes;for(let i=0;i{null===s.transparencyMode&&(s.transparencyMode=0),s.transparencyMode=(s.transparencyMode+1)%3,g[n]=s.transparencyMode,e.textContent=t(s.transparencyMode??0)},r.appendChild(e)}else{const e=document.createElement("button");e.style.float="right",e.style.width="100px",e.style.height="auto",e.style.fontSize="14px",e.style.marginRight="10px",e.style.border="none",e.textContent=s.transparencyMode===Ws.MATERIAL_OPAQUE?"Opaque":"Alpha Blend";const t=i;e.onclick=()=>{s.transparencyMode=s.transparencyMode===Ws.MATERIAL_OPAQUE?Ws.MATERIAL_ALPHABLEND:Ws.MATERIAL_OPAQUE,p[t]=s.transparencyMode===Ws.MATERIAL_ALPHABLEND,e.textContent=s.transparencyMode===Ws.MATERIAL_OPAQUE?"Opaque":"Alpha Blend"},r.appendChild(e)}W.appendChild(r)}function t(e){switch(e){case Ws.MATERIAL_OPAQUE:return"Opaque";case Ws.MATERIAL_ALPHATEST:return"Alpha Test";case Ws.MATERIAL_ALPHABLEND:return"Alpha Blend";default:return"Unknown"}}},H=document.createElement("div");H.style.width="100%",H.style.height="auto",H.style.display="flex",H.style.flexDirection="column",H.style.justifyContent="center",H.style.alignItems="center",H.style.marginBottom="10px",H.style.border="1px solid black",H.style.padding="20px",H.style.boxSizing="border-box",b.appendChild(H);const K=document.createElement("div");K.style.width="100%",K.style.height="30px",K.style.display="flex",K.style.flexDirection="row",K.style.justifyContent="space-between",K.style.alignItems="center",K.style.marginBottom="10px",H.appendChild(K);const Y=document.createElement("label");Y.textContent="Preserve Serialization Data",Y.title="If enabled, the converted file will be larger, but the converted file will be able to be converted back to PMX without any loss of data in technically(currently BPMX to PMX conversion is not supported).",Y.style.textAlign="left",Y.style.marginRight="10px",Y.style.fontSize="16px",K.appendChild(Y);const q=document.createElement("label");q.textContent="(reload required)",q.style.fontSize="11px",q.style.color="gray",q.style.flexGrow="1",K.appendChild(q);const j=document.createElement("input");j.style.width="16px",j.style.height="16px",j.type="checkbox",j.checked=s.preserveSerializationData,K.appendChild(j),j.onclick=e=>{T?e.preventDefault():(s.preserveSerializationData=j.checked,i.preserveSerializationData=j.checked,null!==f&&u(f))};const Z=document.createElement("div");Z.style.width="100%",Z.style.height="30px",Z.style.display="flex",Z.style.flexDirection="row",Z.style.justifyContent="space-between",Z.style.alignItems="center",Z.style.marginBottom="10px",H.appendChild(Z);const Q=document.createElement("label");Q.textContent="Build Skeleton",Q.title="If your model don't need to be animated by skeleton(e.g. stage model), you can disable this option to reduce the size of the converted file. also, it can improve the performance of the converted model.",Q.style.textAlign="left",Q.style.marginRight="10px",Q.style.fontSize="16px",Q.style.flexGrow="1",Z.appendChild(Q);const $=document.createElement("input");$.style.width="16px",$.style.height="16px",$.type="checkbox",$.checked=s.buildSkeleton,Z.appendChild($);const J=document.createElement("div");J.style.width="100%",J.style.height="30px",J.style.display="flex",J.style.flexDirection="row",J.style.justifyContent="space-between",J.style.alignItems="center",J.style.marginBottom="10px",H.appendChild(J);const ee=document.createElement("label");ee.textContent="Build Morph",ee.title="If your model don't need to be animated by morph targets(e.g. stage model), you can disable this option to reduce the size of the converted file. also, it can improve the performance of the converted model.",ee.style.textAlign="left",ee.style.marginRight="10px",ee.style.fontSize="16px",ee.style.flexGrow="1",J.appendChild(ee);const te=document.createElement("input");te.style.width="16px",te.style.height="16px",te.type="checkbox",te.checked=s.buildMorph,J.appendChild(te);const ie=document.createElement("div");ie.style.width="100%",ie.style.height="auto",ie.style.display="flex",ie.style.flexDirection="row",ie.style.justifyContent="space-between",ie.style.alignItems="center",b.appendChild(ie);const se=document.createElement("button");return se.textContent="Convert",se.style.width="100%",se.style.height="60px",se.style.border="none",se.style.fontSize="20px",ie.appendChild(se),se.onclick=async()=>{if(T)return;if(null===f)return;if(null===_)return;T=!0,t.displayLoadingUI(),t.loadingUIText=`


Converting (${f.name})...`;const e=S.convert(_,{includeSkinningData:$.checked,includeMorphData:te.checked,translucentMaterials:p,alphaEvaluateResults:g}),i=new Blob([e],{type:"application/octet-stream"}),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${f.name.substring(0,f.name.lastIndexOf("."))}.bpmx`,r.click(),URL.revokeObjectURL(s),r.remove(),await new Promise((e=>{setTimeout((()=>{t.hideLoadingUI(),e()}),1500)})),T=!1},C.click(),t.resize(!0),n}}},858:(e,t,i)=>{i.d(t,{y:()=>s});class s{_canvas;_engine;_scene;_onTick;constructor(e){this._canvas=e.canvas,this._engine=e.engine,this._scene=null,this._onTick=null}static async Create(e){const t=new s(e);return t._scene=await t._initialize(e.sceneBuilder),t._onTick=t._makeOnTick(),t}run(){const e=this._engine;window.addEventListener("resize",this._onResize),e.runRenderLoop(this._onTick)}dispose(){window.removeEventListener("resize",this._onResize),this._engine.dispose()}_onResize=()=>{this._engine.resize()};async _initialize(e){return await e.build(this._canvas,this._engine)}_makeOnTick(){const e=this._scene;return()=>e.render()}}},485:(e,t,i)=>{i.a(e,(async(e,t)=>{try{var s=i(610),r=i(858),n=i(979);await new Promise((e=>window.onload=e));const e=document.createElement("canvas");e.style.width="100%",e.style.height="100%",e.style.display="block",document.body.appendChild(e);const a=new s.N(e,!1,{preserveDrawingBuffer:!1,stencil:!0,antialias:!0,alpha:!1,premultipliedAlpha:!1,powerPreference:"high-performance",doNotHandleTouchAction:!0,doNotHandleContextLost:!0,audioEngine:!1,disableWebGL2Support:!1},!0);r.y.Create({canvas:e,engine:a,sceneBuilder:new n.u}).then((e=>e.run())),t()}catch(e){t(e)}}),1)},504:(e,t,i)=>{i.d(t,{n:()=>s});class s{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=s._Counter++}}s._Counter=0},696:(e,t,i)=>{i(326).$.prototype.createDepthStencilTexture=function(e,t,i){if(t.isCube){const i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t,i)}},212:(e,t,i)=>{var s=i(321);s.w.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,a=!0,o=!1,h=0,l=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let d=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return o?n||(n=function(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}(e.type,4*t*i)):d===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),d=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),d=c.FLOAT),a&&this.flushFramebuffer(),c.readPixels(h,l,t,i,c.RGBA,d,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},s.w.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,a=!0,o=!1,h=0,l=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,a,o,h,l))}},125:(e,t,i)=>{i.d(t,{nO:()=>S,pB:()=>M,M0:()=>b,Iq:()=>P,J:()=>D});class s{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let s=this.line;const r=t.processor;if(r){r.lineProcessor&&(s=r.lineProcessor(s,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";!t.isFragment&&r.attributeProcessor&&this.line.startsWith(i)?s=r.attributeProcessor(this.line,e,t.processingContext):r.varyingProcessor&&(r.varyingCheck?.(this.line,t.isFragment)||!r.varyingCheck&&this.line.startsWith(n))?s=r.varyingProcessor(this.line,t.isFragment,e,t.processingContext):r.uniformProcessor&&r.uniformRegexp&&r.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&r.uniformBufferRegexp&&r.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):r.textureProcessor&&r.textureRegexp&&r.textureRegexp.test(this.line)?s=r.textureProcessor(this.line,t.isFragment,e,t.processingContext):(r.uniformProcessor||r.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?r.uniformProcessor&&(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r.endOfUniformBufferProcessor&&(s=r.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=s+"\n"}return this.children.forEach((s=>{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class r{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{c=c.trim(),""!==c&&(i.push(c),c="")},n=e=>{so._Stack[s],h=()=>-1===s?"!!INVALID EXPRESSION!!":o._Stack[s--];let l=0,c="";for(;l1){for(r();-1!==s&&o._OperatorPriority[a()]>=o._OperatorPriority[d];)i.push(h());n(d),l++}else c+=t;l++}for(r();-1!==s;)"("===a()?h():i.push(h());return o._InfixToPostfixCache.size>=o.InfixToPostfixCacheLimitSize&&o.ClearCache(),o._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(o._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var u=i(503),f=i(662),_=i(741);const p=/defined\s*?\((.+?)\)/g,g=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,T=/__decl__/,x=/light\{X\}.(\w*)/g,E=/\{X\}/g,v=[],A=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function M(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function b(e,t,i,n){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),P(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const a=function(e,t,i){let n=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return n;if(t.processor.shaderLanguage===f.w.GLSL&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const a=t.defines,o=function(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===f.w.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",(0,_.xt)(s,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),s}(t,i);return t.processor.preProcessor&&(n=t.processor.preProcessor(n,a,o,t.isFragment,t.processingContext)),n=function(e,t,i){const n=new s,a=new r;return a.lineIndex=-1,a.lines=e.split("\n"),C(a,n),n.process(t,i)}(n,o,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}(e,t,n);i(a,e)}))}function S(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function y(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new h(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new h(e);const n=e.substring(0,r).trim(),a=e.substring(r+s.length).trim();return new d(n,s,a)}function I(e,t){const i=new a,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new h(r):"#ifndef"===s?new h(r,!0):function(e){e=e.replace(p,"defined[$1]");const t=o.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new c:new l;"string"==typeof t&&(t=t.replace(g,"defined($1)")),"string"==typeof s&&(s=s.replace(g,"defined($1)")),r.leftOperand="string"==typeof s?y(s):s,r.rightOperand="string"==typeof t?y(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(g,"defined($1)")),"string"==typeof s?y(s):s}(r),i}function R(e,t,i){let r=e.currentLine;for(;C(e,i);){r=e.currentLine;const n=r.substring(0,5).toLowerCase();if("#else"===n){const i=new s;return t.children.push(i),void C(e,i)}if("#elif"===n){const e=I(r,5);t.children.push(e),i=e}}}function C(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=A.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new n;t.children.push(s);const r=I(i,6);s.children.push(r),R(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new n;t.children.push(s);const r=I(i,7);s.children.push(r),R(e,s,r);break}case"#if":{const s=new n,r=I(i,3);t.children.push(s),s.children.push(r),R(e,s,r);break}}continue}}const r=new s;if(r.line=i,t.children.push(r),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");r.additionalDefineKey=e[1],3===e.length&&(r.additionalDefineValue=e[2])}}return!1}function P(e,t,i){let s;for(v.length=0;null!==(s=m.exec(e));)v.push(s);let r=String(e),n=[e],a=!1;for(const e of v){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(T,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void D.loadFile(e,(e=>{t.includesShadersStore[s]=e,P(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=a.replace(E,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(x,((e,t)=>t+"{X}"))),i=i.replace(E,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}v.length=0,r=n.join(""),a?P(r.toString(),t,i):i(r)}const D={loadFile:(e,t,i,s,r,n)=>{throw(0,u.n)("FileTools")}}},716:(e,t,i)=>{i.d(t,{d:()=>s});class s{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},741:(e,t,i)=>{i.d(t,{W0:()=>a,iL:()=>n,sg:()=>r,xt:()=>o});var s=i(503);i(790);const r={};function n(e,t,i=""){return i+(t?t+"\n":"")+e}function a(e,t,i,n,a,o,h){const l=h||r.loadFile;if(l)return l(e,t,i,n,a,o);throw(0,s.n)("FileTools")}function o(e,t,i,s){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(s?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),s&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}},326:(e,t,i)=>{i.d(t,{$:()=>T,r:()=>m});var s=i(315),r=i(137),n=i(420),a=i(215),o=i(237);class h{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class l{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class c{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=c.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=c.KEEP,this.opDepthFail=c.KEEP,this.opStencilDepthPass=c.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}c.ALWAYS=519,c.KEEP=7680,c.REPLACE=7681;class d{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,s){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===s||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=s,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,s){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===s||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=s,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}var u=i(503),f=i(854),_=i(790),p=i(848),g=i(741);function m(e,t){if((0,_.BA)()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}class T{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,this._depthCullingState.depthFunc=e?518: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)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_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()}n.M.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){r.V.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,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,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)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,(0,_.BA)()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)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&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(S).toLowerCase():""),I=null;y.indexOf("?")>-1&&(y=y.split("?")[0]);for(const e of T._TextureLoaders)if(e.canLoad(y,g)){I=e;break}n&&n.addPendingData(M),M.url=e,M.generateMipMaps=!t,M.samplingMode=a,M.invertY=i,M._useSRGBBuffer=this._getUseSRGBBuffer(!!x,t),this._doNotHandleContextLost||(M._buffer=d);let R=null;o&&!u&&(R=M.onLoadedObservable.add(o)),u||this._internalTexturesCache.push(M);const C=(i,u)=>{n&&n.removePendingData(M),e===b?(R&&M.onLoadedObservable.remove(R),s.q.UseFallbackTexture&&e!==s.q.FallbackTexture&&this._createTextureBase(s.q.FallbackTexture,t,M.invertY,n,a,null,h,l,c,d,M),i=(i||"Unknown error")+(s.q.UseFallbackTexture?" - Fallback texture was used":""),M.onErrorObservable.notifyObservers({message:i,exception:u}),h&&h(i,u)):(r.V.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,M.invertY,n,a,o,h,l,c,d,M,_,p,g,m,x))};if(I){const t=e=>{I.loadData(e,M,((e,t,i,s,r,o)=>{o?C("TextureLoader failed to load data"):l(M,y,n,{width:e,height:t},M.invertY,!i,s,(()=>(r(),!1)),a)}),m)};d?d instanceof ArrayBuffer?t(new Uint8Array(d)):ArrayBuffer.isView(d)?t(d):h&&h("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,n?n.offlineProvider:void 0,!0,((e,t)=>{C("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{v&&!this._doNotHandleContextLost&&(M._buffer=e),l(M,y,n,e,M.invertY,t,!1,c,a)};!E||A?d&&("string"==typeof d.decoding||d.close)?i(d):T._FileToolsLoadImage(e||"",i,C,n?n.offlineProvider:null,g,M.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof d||d instanceof ArrayBuffer||ArrayBuffer.isView(d)||d instanceof Blob?T._FileToolsLoadImage(d,i,C,n?n.offlineProvider:null,g,M.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):d&&i(d)}return M}_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:(0,_.Nf)()?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.10.2"}static get Version(){return"7.10.2"}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){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new h,this._stencilStateComposer=new l,this._stencilState=new c,this._alphaState=new d,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 p.cP,this.onCanvasFocusObservable=new p.cP,this.onNewSceneAddedObservable=new p.cP,this.onResizeObservable=new p.cP,this.onCanvasPointerOutObservable=new p.cP,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 p.cP,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new p.cP,this.onAfterShaderCompilationObservable=new p.cP,this.onBeginFrameObservable=new p.cP,this.onEndFrameObservable=new p.cP,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new p.cP,this.onContextRestoredObservable=new p.cP,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 p.cP,s.q.Instances.push(this),this.startTime=o.j.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,a.I.SetMatrixPrecision(!!t.useHighPrecisionMatrix),(0,_.XD)()&&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??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const r=(0,_.BA)()&&window.devicePixelRatio||1,n=t.limitDeviceRatio||r;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(n,r):1,this._lastDevicePixelRatio=r,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=(0,_.BA)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,_.BA)()&&(0,_.Nf)())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.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)return!1;if(e|=0,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 e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,_.Nf)()&&"ontouchend"in document},this._checkForMobile(),(0,_.BA)()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_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("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return T._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n){throw(0,u.n)("FileTools")}_loadFile(e,t,i,s,r,n){const a=(0,g.W0)(e,t,i,s,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(a);-1!==e&&this._activeRequests.splice(e,1)})),a}static _FileToolsLoadFile(e,t,i,s,r,n){if(g.sg.loadFile)return g.sg.loadFile(e,t,i,s,r,n);throw(0,u.n)("FileTools")}dispose(){for(this.hideLoadingUI(),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();this.releaseComputeEffects?.(),n.M.ResetCache();for(const e of this._activeRequests)e.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(),(0,_.BA)()&&window.removeEventListener("resize",this._checkForMobile);const e=s.q.Instances.indexOf(this);e>=0&&s.q.Instances.splice(e,1),s.q.Instances.length||(s.q.OnEnginesDisposedObservable.notifyObservers(this),s.q.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw(0,u.n)("LoadingScreen")}}T._TextureLoaders=[],T._RenderPassIdCounter=0,T._RescalePostProcessFactory=null},610:(e,t,i)=>{i.d(t,{N:()=>T});var s=i(854),r=i(315),n=i(321),a=i(237);class o{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new h(e)}sampleFrame(e=a.j.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){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 0===e?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 h{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-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}}var l=i(329),c=i(137),d=i(716);n.w.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){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: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 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 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}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},i(212),n.w.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},n.w.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};var u=i(790),f=i(326);function _(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}f.$.prototype.displayLoadingUI=function(){if(!(0,u.BA)())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},f.$.prototype.hideLoadingUI=function(){if(!(0,u.BA)())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(f.$.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=f.$.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(f.$.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(f.$.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),f.$.prototype.getInputElement=function(){return this._renderingCanvas},f.$.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},f.$.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},f.$.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},f.$.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},f.$.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},f.$.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},f.$.prototype.getInputElement=function(){return this._renderingCanvas},f.$.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},f.$.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},f.$.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},f.$.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},f.$.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},f.$.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},f.$.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},f.$.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},f.$.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},f.$.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},f.$.prototype.getStencilMask=function(){return this._stencilState.stencilMask},f.$.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},f.$.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},f.$.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},f.$.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},f.$.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},f.$.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},f.$.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},f.$.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},f.$.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},f.$.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},f.$.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},f.$.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},f.$.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},f.$.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},f.$.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},f.$.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},f.$.prototype.getAlphaMode=function(){return this._alphaMode},f.$.prototype.getAlphaEquation=function(){return this._alphaEquation},f.$.prototype.getRenderPassNames=function(){return this._renderPassNames},f.$.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},f.$.prototype.createRenderPassId=function(e){const t=++f.$._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},f.$.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;tnew m(e,t,i);class m{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 g.cP,this.onAudioLockedObservable=new g.cP,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,u.BA)())return;void 0!==window.AudioContext&&(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(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContextOnStateChange(){this._audioContext?.addEventListener("statechange",(()=>{this.unlocked&&"running"!==this._audioContext?.state&&this._resumeAudioContext()}),{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){return this._audioContext?.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,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,c.V.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 e=".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) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),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 T extends n.w{static get NpmPackage(){return f.$.NpmPackage}static get Version(){return f.$.Version}static get Instances(){return r.q.Instances}static get LastCreatedEngine(){return r.q.LastCreatedEngine}static get LastCreatedScene(){return r.q.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const s=e.getHostWindow();s&&"function"==typeof s.addEventListener&&(s.addEventListener("blur",e._onBlur),s.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!f.$.audioEngine&&i.audioEngine&&f.$.AudioEngineFactory&&(f.$.audioEngine=f.$.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),(0,u.Nf)()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&_(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==f.$.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return function(e,t,i,s){const r=e.createCanvas(i,s).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,i,s).data}(this,e,t,i)}_createImageBitmapFromSource(e,t){return function(e,t,i){return new Promise(((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{s(e)}))}))},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t}))}(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&function(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&function(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}()}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 r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,s),r}scissorClear(e,t,i,s,r){this.enableScissor(e,t,i,s),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,s){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,s)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_loadFileAsync(e,t,i){return new Promise(((s,r)=>{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}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 function(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){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&&0===this._frameHandler&&(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&&_(this._renderingCanvas)}exitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}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,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,s,r){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 n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&T._RescalePostProcessFactory&&(this._rescalePostProcess=T._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}wrapWebGLTexture(e,t=!1,i=3,r=0,n=0){const a=new d.d(e,this._gl),o=new s.h(this,s.G.Unknown,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=n,o.width=r,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let l=r.TEXTURE_2D;e.isCube&&(l=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(l,s,o,a,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void c.V.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(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),0===t?(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 l.A(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const a=()=>{const o=s.clientWaitSync(e,t,0);o!=s.WAIT_FAILED?o!=s.TIMEOUT_EXPIRED?r():setTimeout(a,i):n()};a()}))}_readPixelsAsync(e,t,i,s,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const o=this._gl,h=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,s,r,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const l=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return l?(o.flush(),this._clientWaitAsync(l,0,10).then((()=>(o.deleteSync(l),o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(h),a)))):null}dispose(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),function(e,t){1===r.q.Instances.length&&f.$.audioEngine&&(f.$.audioEngine.dispose(),f.$.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),(0,u.Nf)()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}(this,this._renderingCanvas),super.dispose()}}T.ALPHA_DISABLE=0,T.ALPHA_ADD=1,T.ALPHA_COMBINE=2,T.ALPHA_SUBTRACT=3,T.ALPHA_MULTIPLY=4,T.ALPHA_MAXIMIZED=5,T.ALPHA_ONEONE=6,T.ALPHA_PREMULTIPLIED=7,T.ALPHA_PREMULTIPLIED_PORTERDUFF=8,T.ALPHA_INTERPOLATE=9,T.ALPHA_SCREENMODE=10,T.DELAYLOADSTATE_NONE=0,T.DELAYLOADSTATE_LOADED=1,T.DELAYLOADSTATE_LOADING=2,T.DELAYLOADSTATE_NOTLOADED=4,T.NEVER=512,T.ALWAYS=519,T.LESS=513,T.EQUAL=514,T.LEQUAL=515,T.GREATER=516,T.GEQUAL=518,T.NOTEQUAL=517,T.KEEP=7680,T.REPLACE=7681,T.INCR=7682,T.DECR=7683,T.INVERT=5386,T.INCR_WRAP=34055,T.DECR_WRAP=34056,T.TEXTURE_CLAMP_ADDRESSMODE=0,T.TEXTURE_WRAP_ADDRESSMODE=1,T.TEXTURE_MIRROR_ADDRESSMODE=2,T.TEXTUREFORMAT_ALPHA=0,T.TEXTUREFORMAT_LUMINANCE=1,T.TEXTUREFORMAT_LUMINANCE_ALPHA=2,T.TEXTUREFORMAT_RGB=4,T.TEXTUREFORMAT_RGBA=5,T.TEXTUREFORMAT_RED=6,T.TEXTUREFORMAT_R=6,T.TEXTUREFORMAT_RG=7,T.TEXTUREFORMAT_RED_INTEGER=8,T.TEXTUREFORMAT_R_INTEGER=8,T.TEXTUREFORMAT_RG_INTEGER=9,T.TEXTUREFORMAT_RGB_INTEGER=10,T.TEXTUREFORMAT_RGBA_INTEGER=11,T.TEXTURETYPE_UNSIGNED_BYTE=0,T.TEXTURETYPE_UNSIGNED_INT=0,T.TEXTURETYPE_FLOAT=1,T.TEXTURETYPE_HALF_FLOAT=2,T.TEXTURETYPE_BYTE=3,T.TEXTURETYPE_SHORT=4,T.TEXTURETYPE_UNSIGNED_SHORT=5,T.TEXTURETYPE_INT=6,T.TEXTURETYPE_UNSIGNED_INTEGER=7,T.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,T.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,T.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,T.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,T.TEXTURETYPE_UNSIGNED_INT_24_8=12,T.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,T.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,T.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,T.TEXTURE_NEAREST_SAMPLINGMODE=1,T.TEXTURE_BILINEAR_SAMPLINGMODE=2,T.TEXTURE_TRILINEAR_SAMPLINGMODE=3,T.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,T.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,T.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,T.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,T.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,T.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,T.TEXTURE_NEAREST_LINEAR=7,T.TEXTURE_NEAREST_NEAREST=1,T.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,T.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,T.TEXTURE_LINEAR_LINEAR=2,T.TEXTURE_LINEAR_NEAREST=12,T.TEXTURE_EXPLICIT_MODE=0,T.TEXTURE_SPHERICAL_MODE=1,T.TEXTURE_PLANAR_MODE=2,T.TEXTURE_CUBIC_MODE=3,T.TEXTURE_PROJECTION_MODE=4,T.TEXTURE_SKYBOX_MODE=5,T.TEXTURE_INVCUBIC_MODE=6,T.TEXTURE_EQUIRECTANGULAR_MODE=7,T.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,T.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,T.SCALEMODE_FLOOR=1,T.SCALEMODE_NEAREST=2,T.SCALEMODE_CEILING=3},315:(e,t,i)=>{i.d(t,{q:()=>r});var s=i(848);class r{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}r.Instances=[],r.OnEnginesDisposedObservable=new s.cP,r._LastCreatedScene=null,r.UseFallbackTexture=!0,r.FallbackTexture=""},215:(e,t,i)=>{i.d(t,{I:()=>s});class s{static SetMatrixPrecision(e){if(s.MatrixTrackPrecisionChange=!1,e&&!s.MatrixUse64Bits&&s.MatrixTrackedMatrices)for(let e=0;e{i.d(t,{l:()=>r});var s=i(662);class r{static GetShadersRepository(e=s.w.GLSL){return e===s.w.GLSL?r.ShadersRepository:r.ShadersRepositoryWGSL}static GetShadersStore(e=s.w.GLSL){return e===s.w.GLSL?r.ShadersStore:r.ShadersStoreWGSL}static GetIncludesShadersStore(e=s.w.GLSL){return e===s.w.GLSL?r.IncludesShadersStore:r.IncludesShadersStoreWGSL}}r.ShadersRepository="src/Shaders/",r.ShadersStore={},r.IncludesShadersStore={},r.ShadersRepositoryWGSL="src/ShadersWGSL/",r.ShadersStoreWGSL={},r.IncludesShadersStoreWGSL={}},852:(e,t,i)=>{i.d(t,{tI:()=>u,bS:()=>T,tg:()=>f,YM:()=>_,C5:()=>m,GX:()=>d,kf:()=>l,EX:()=>c,Cm:()=>h,N5:()=>o});class s{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))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,r,n,a,o){const h=this.engine;if(h.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let l;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,l=0;l{n[e]=t}));for(const e of h.getAttributes(this,a))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==s&&(n[2]=s,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.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];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}var r=i(741);const n=new WeakMap,a={_webGLVersion:2,cachedPipelines:{}};function o(e){let t=n.get(e);if(!t){if(!e)return a;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},n.set(e,t)}return t}function h(e){n.delete(e)}function l(e,t,i,s,r,n){const a=o(s);return n||(n=a._createShaderProgramInjection??u),n(e,g(t,"vertex",s,a._contextWasLost),g(i,"fragment",s,a._contextWasLost),s,r,a.validateShaderPrograms)}function c(e,t,i,s,r,n=null,a){const h=o(r);a||(a=h._createShaderProgramInjection??u);const l=h._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return a(e,p(t,"vertex",s,l,r,h._contextWasLost),p(i,"fragment",s,l,r,h._contextWasLost),r,n,h.validateShaderPrograms)}function d(e,t){const i=new s,r=o(e);return r.parallelShaderCompile&&(i.isParallelCompiled=!0),i.context=r._context,i}function u(e,t,i,s,r=null,n){const a=s.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return s.attachShader(a,t),s.attachShader(a,i),s.linkProgram(a),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||f(e,s,n),a}function f(e,t,i){const s=e.context,r=e.vertexShader,n=e.fragmentShader,a=e.program;if(!s.getProgramParameter(a,s.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=s.getProgramInfoLog(a);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(s.validateProgram(a),!s.getProgramParameter(a,s.VALIDATE_STATUS))){const t=s.getProgramInfoLog(a);if(t)throw e.programValidationError=t,new Error(t)}s.deleteShader(r),s.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function _(e,t,i,s,r,n,a,h,d,u="",f,_){const p=o(e.context);f||(f=p.createRawShaderProgramInjection??l),_||(_=p.createShaderProgramInjection??c);const g=e;g.program=s?f(g,t,i,g.context,d):_(g,t,i,h,g.context,d),g.program.__SPECTOR_rebuildProgram=a}function p(e,t,i,s,n,a){return g((0,r.iL)(e,i,s),t,n,a)}function g(e,t,i,s){const r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${s}`)}return i.shaderSource(r,e),i.compileShader(r),r}function m(e,t){t.useProgram(e)}function T(e,t){const i=e;if(!i.isParallelCompiled)return void t(e);const s=i.onCompiled;i.onCompiled=()=>{s?.(),t(e)}}},321:(e,t,i)=>{i.d(t,{w:()=>x});var s=i(852),r=i(137),n=i(790),a=i(662);class o{constructor(){this.shaderLanguage=a.w.GLSL}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const h=/(flat\s)?\s*varying\s*.*/;class l{constructor(){this.shaderLanguage=a.w.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return h.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}var c=i(329),d=i(597),u=i(326),f=i(716),_=i(854),p=i(420),g=i(741),m=i(647);class T{}class x extends u.${get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return p.M.ShadersRepository}static set ShadersRepository(e){p.M.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!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,n){if(i=i||{},super(t??i.antialias,i,n),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 a=null;if(e.getContext){if(a=e,this._renderingCanvas=a,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of x.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,r.V.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},a.addEventListener("webglcontextlost",this._onContextLost,!1),a.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=a.getContext("webgl2",i)||a.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!a)throw new Error("The provided canvas is null or undefined.");try{this._gl=a.getContext("webgl",i)||a.getContext("experimental-webgl",i)}catch(e){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 t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new l:new o;const h=`Babylon.js v${x.Version}`;r.V.Log(h+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",h);const c=(0,s.N5)(this._gl);c.validateShaderPrograms=this.validateShaderPrograms,c.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(){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||null!==this._gl.getExtension("OES_standard_derivatives"),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||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),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:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(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"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.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 e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,a){const o=this._currentBufferPointers[t];if(!o)return;let h=!1;o.active?(o.buffer!==e&&(o.buffer=e,h=!0),o.size!==i&&(o.size=i,h=!0),o.type!==s&&(o.type=s,h=!0),o.normalized!==r&&(o.normalized=r,h=!0),o.stride!==n&&(o.stride=n,h=!0),o.offset!==a&&(o.offset=a,h=!0)):(h=!0,o.active=!0,o.index=t,o.size=i,o.type=s,o.normalized=r,o.stride=n,o.offset=a,o.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,a):this._gl.vertexAttribPointer(t,i,s,r,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let a=null;if(i&&(a=i[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const o=a.getBuffer();o&&(this._vertexAttribPointer(o,n,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[a],this._gl.FLOAT,!1,s,n)),n+=4*i[a]}}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)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(h=1),1!==o||this._caps.textureFloat||(o=0,r.V.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,f=new _.h(this,s),p=e.width||e,g=e.height||e,m=e.depth||0,T=e.layers||0,x=this._getSamplingParameters(h,a),E=0!==T?u.TEXTURE_2D_ARRAY:0!==m?u.TEXTURE_3D:u.TEXTURE_2D,v=this._getRGBABufferInternalSizedFormat(o,l,c),A=this._getInternalFormat(l),M=this._getWebGLTextureType(o);return this._bindTextureDirectly(E,f),0!==T?(f.is2DArray=!0,u.texImage3D(E,0,v,p,g,T,0,A,M,null)):0!==m?(f.is3D=!0,u.texImage3D(E,0,v,p,g,m,0,A,M,null)):u.texImage2D(E,0,v,p,g,0,A,M,null),u.texParameteri(E,u.TEXTURE_MAG_FILTER,x.mag),u.texParameteri(E,u.TEXTURE_MIN_FILTER,x.min),u.texParameteri(E,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(E,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(E),this._bindTextureDirectly(E,null),f._useSRGBBuffer=c,f.baseWidth=p,f.baseHeight=g,f.width=p,f.height=g,f.depth=T,f.isReady=!0,f.samples=d,f.generateMipMaps=a,f.samplingMode=h,f.type=o,f.format=l,f.label=n,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,a=null,o=null,h=null,l=null,c=null,d,u,f,p){return this._createTextureBase(e,t,i,s,r,n,a,((...e)=>this._prepareWebGLTexture(...e,l)),((e,t,i,r,n,a)=>{const o=this._gl,h=i.width===e&&i.height===t;n._creationFlags=f??0;const l=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(h)return o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new _.h(this,_.G.Temp);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,i),this._rescaleTexture(e,n,s,l.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,n,!0),a()}))}return!0}),o,h,l,c,d,u,p)}_getTexImageParametersForCreateTexture(e,t){let i,s;return 1===this.webGLVersion?(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,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,a=0){const o=this._gl;let h=o.TEXTURE_2D;if(e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(h,a,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),l=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);const d=Math.round(Math.log(e.width)*Math.LOG2E),u=Math.round(Math.log(e.height)*Math.LOG2E),f=n?e.width:Math.pow(2,Math.max(d-s,0)),_=n?e.height:Math.pow(2,Math.max(u-s,0));a.texImage2D(c,s,l,f,_,0,h,o,t)}updateTextureData(e,t,i,s,r,n,a=0,o=0,h=!1){const l=this._gl,c=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let u=l.TEXTURE_2D,f=l.TEXTURE_2D;e.isCube&&(f=l.TEXTURE_CUBE_MAP_POSITIVE_X+a,u=l.TEXTURE_CUBE_MAP),this._bindTextureDirectly(u,e,!0),l.texSubImage2D(f,o,i,s,r,n,d,c,t),h&&this._gl.generateMipmap(f),this._bindTextureDirectly(u,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const a=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,a,o,h,l){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?(0,d.R)(s.width,c):s.width),f=Math.min(c,this.needPOTTextures?(0,d.R)(s.height,c):s.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=f,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:l??(".jpg"!==t||e._useSRGBBuffer?5:4),o(u,f,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,a,h)}))||this._prepareWebGLTextureContinuation(e,i,n,a,h)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,i,s,r,n,a)}_updateRenderBuffer(e,t,i,s,r,n,a,o=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),s>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,s,n,t,i):h.renderbufferStorage(h.RENDERBUFFER,r,t,i),h.framebufferRenderbuffer(h.FRAMEBUFFER,a,h.RENDERBUFFER,e),o&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&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&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&((0,s.C5)(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw r.V.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(n=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_bindTexture(e,t,i){if(void 0===e)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){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(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 i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(o,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(o,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){(0,n.BA)()&&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&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),(0,s.Cm)(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 r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}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}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;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;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;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;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;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:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,r=!0,n=!0){const a=r?4:3,o=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(s*i*a);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,o,this._gl.UNSIGNED_BYTE,h),Promise.resolve(h)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=u.$._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}x._TempClearColorUint32=new Uint32Array(4),x._TempClearColorInt32=new Int32Array(4),x.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"]}],x.CollisionsEpsilon=.001,x._ConcatenateShader=g.iL,x._IsSupported=null,x._HasMajorPerformanceCaveat=null,x.CeilingPOT=d.Tg,x.FloorPOT=d.C4,x.NearestPOT=d.OG,x.GetExponentOfTwo=d.R,x.QueueNewFrame=u.r},854:(e,t,i)=>{i.d(t,{h:()=>a,G:()=>s});var s,r=i(848);class n{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,r=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=s,this.samplingMode=r,this._comparisonFunction=n,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}}!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth"}(s||(s={}));class a extends n{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 r.cP,this.onErrorObservable=new r.cP,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=s.Unknown,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._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._engine=e,this._source=t,this._uniqueId=a._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(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case s.Temp:break;case s.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case s.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case s.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case s.Cube:return void(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));case s.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case s.CubeRawRGBD:return;case s.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case s.DepthStencil:case s.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.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);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}a._Counter=0},647:(e,t,i)=>{i.d(t,{b4:()=>c,bu:()=>u,mO:()=>d,uR:()=>_});var s=i(790),r=i(662),n=i(852),a=i(229),o=i(137),h=i(125),l=i(741);function c(e,t){return(0,n.N5)(t).cachedPipelines[e]}function d(e){const t=e._name,i=e.context;if(t&&i){const e=(0,n.N5)(i),s=e.cachedPipelines[t];s?.dispose(),delete e.cachedPipelines[t]}}function u(e,t,i,n,a,o,l){let c,d;const u=(0,s.BA)()?o?.getHostDocument():null;c="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?u?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,d="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?u?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const _=[void 0,void 0],p=()=>{if(_[0]&&_[1]){e.isFragment=!0;const[s,c]=_;(0,h.M0)(c,e,((o,c)=>{l&&(l._fragmentSourceCodeBeforeMigration=c),i&&(o=i("fragment",o));const d=(0,h.nO)(s,o,e);e=null;const u=function(e,t,i,s){if(i){const n=i.vertexElement||i.vertex||i.spectorName||i,a=i.fragmentElement||i.fragment||i.spectorName||i;return{vertexSourceCode:(s===r.w.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,fragmentSourceCode:(s===r.w.WGSL?"//":"")+"#define SHADER_NAME fragment:"+a+"\n"+t}}return{vertexSourceCode:e,fragmentSourceCode:t}}(d.vertexCode,d.fragmentCode,t,a);n?.(u.vertexSourceCode,u.fragmentSourceCode)}),o)}};f(c,"Vertex","",(t=>{(0,h.pB)(e),(0,h.M0)(t,e,((e,s)=>{l&&(l._rawVertexSourceCode=t,l._vertexSourceCodeBeforeMigration=s),i&&(e=i("vertex",e)),_[0]=e,p()}),o)}),a),f(d,"Fragment","Pixel",(e=>{l&&(l._rawFragmentSourceCode=e),_[1]=e,p()}),a)}function f(e,t,i,r,n,o){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void r((0,s.Zl)(e));if("source:"===e.substr(0,7))return void r(e.substr(7));if("base64:"===e.substr(0,7))return void r(window.atob(e.substr(7)));const h=a.l.GetShadersStore(n);if(h[e+t+"Shader"])return void r(h[e+t+"Shader"]);if(i&&h[e+i+"Shader"])return void r(h[e+i+"Shader"]);let c;if(c="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:a.l.GetShadersRepository(n)+e,!(o=o||l.W0))throw new Error("loadFileInjection is not defined");o(c+"."+t.toLowerCase()+".fx",r)}const _=(e,t,i,s)=>{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&((0,n.N5)(e.context).cachedPipelines[e.name]=r),i(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),s(r,(()=>{e.onRenderingStateCompiled?.(r)})),r}catch(e){throw o.V.Error("Error compiling effect"),e}}},420:(e,t,i)=>{i.d(t,{M:()=>h});var s=i(848),r=i(137),n=i(229),a=i(662),o=i(647);class h{static get ShadersRepository(){return n.l.ShadersRepository}static set ShadersRepository(e){n.l.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new s.cP),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r=null,n,l=null,c=null,d=null,u=null,f,_="",p=a.w.GLSL){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new s.cP,this.onErrorObservable=new s.cP,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=_;const g=this._key.replace(/\r/g,"").replace(/\n/g,"|");let m;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??a.w.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}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){this.isReady()?e(this):(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){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??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=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,s),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:a._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},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(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&2===n.length){const t=parseInt(n[1]),s=e.split("\n",-1);s.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(r.V.Error("Unable to compile effect:"),r.V.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),r.V.Error("Attributes: "+i.map((function(e){return" "+e}))),r.V.Error("Defines:\n"+this.defines),h.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(r.V.Error("Vertex code:"),r.V.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(r.V.Error("Fragment code:"),r.V.Error(i))),e&&r.V.Error(e),t&&r.V.Error(t)}r.V.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,r.V.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(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{var s;i.d(t,{w:()=>s}),function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(s||(s={}))},329:(e,t,i)=>{i.d(t,{A:()=>r});var s=i(504);class r extends s.n{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},503:(e,t,i)=>{i.d(t,{n:()=>r});const s={};function r(e,t=!1){if(!t||!s[e])return s[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}},790:(e,t,i)=>{function s(){return"undefined"!=typeof window}function r(){return"undefined"!=typeof navigator}function n(){return"undefined"!=typeof document}function a(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}i.d(t,{BA:()=>s,Nf:()=>n,XD:()=>r,Zl:()=>a})},137:(e,t,i)=>{i.d(t,{V:()=>s});class s{static _CheckLimit(e,t){let i=s._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},s._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){const i=s._LogLimitOutputs[e];if(!i||!s.MessageLimitReached)return;const r=this._Levels[t];i.current===i.limit&&s[r.name](s.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,r.name??""))}static _AddLogEntry(e){s._LogCache=e+s._LogCache,s.OnNewCacheEntry&&s.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const r=Array.isArray(t)?t[0]:t;if(void 0!==i&&!s._CheckLimit(r,i))return;const n=s._FormatMessage(r),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+n,...o);const h=`
${n}

`;s._AddLogEntry(h),s._GenerateLimitMessage(r,e)}static get LogCache(){return s._LogCache}static ClearLogCache(){s._LogCache="",s._LogLimitOutputs={},s.errorsCount=0}static set LogLevels(e){s.Log=s._LogDisabled,s.Warn=s._LogDisabled,s.Error=s._LogDisabled,[s.MessageLogLevel,s.WarningLogLevel,s.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];s[e.name]=s._LogEnabled.bind(s,t)}}))}}s.NoneLogLevel=0,s.MessageLogLevel=1,s.WarningLogLevel=2,s.ErrorLogLevel=4,s.AllLogLevel=7,s.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",s._LogCache="",s._LogLimitOutputs={},s._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],s.errorsCount=0,s.Log=s._LogEnabled.bind(s,s.MessageLogLevel),s.Warn=s._LogEnabled.bind(s,s.WarningLogLevel),s.Error=s._LogEnabled.bind(s,s.ErrorLogLevel)},848:(e,t,i)=>{i.d(t,{cP:()=>n});class s{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 r{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 n{static FromPromise(e,t){const i=new n;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),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 s(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,n=!1){if(!e)return null;const a=new r(e,t,s);return a.unregisterOnNextCall=n,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}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-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new n;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}}},296:(e,t,i)=>{i.d(t,{A:()=>r});var s=i(237);class r{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){r.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){r.Enabled&&(this._startMonitoringTime=s.j.Now)}endMonitoring(e=!0){if(!r.Enabled)return;e&&this.fetchNewFrame();const t=s.j.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=s.j.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}r.Enabled=!0},237:(e,t,i)=>{i.d(t,{j:()=>r});var s=i(790);class r{static get Now(){return(0,s.BA)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},597:(e,t,i)=>{function s(e){let t=1;do{t*=2}while(te-i?i:t}function a(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function o(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function h(e,t,i=2){let s;switch(i){case 1:s=o(e);break;case 2:s=n(e);break;default:s=a(e)}return Math.min(s,t)}i.d(t,{C4:()=>o,L8:()=>s,OG:()=>n,R:()=>h,Tg:()=>a,zF:()=>r})}},n={};function a(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e](i,i.exports,a),i.exports}e="function"==typeof Symbol?Symbol("webpack queues"):"__webpack_queues__",t="function"==typeof Symbol?Symbol("webpack exports"):"__webpack_exports__",i="function"==typeof Symbol?Symbol("webpack error"):"__webpack_error__",s=e=>{e&&e.d<1&&(e.d=1,e.forEach((e=>e.r--)),e.forEach((e=>e.r--?e.r++:e())))},a.a=(r,n,a)=>{var o;a&&((o=[]).d=-1);var h,l,c,d=new Set,u=r.exports,f=new Promise(((e,t)=>{c=t,l=e}));f[t]=u,f[e]=e=>(o&&e(o),d.forEach(e),f.catch((e=>{}))),r.exports=f,n((r=>{var n;h=(r=>r.map((r=>{if(null!==r&&"object"==typeof r){if(r[e])return r;if(r.then){var n=[];n.d=0,r.then((e=>{a[t]=e,s(n)}),(e=>{a[i]=e,s(n)}));var a={};return a[e]=e=>e(n),a}}var o={};return o[e]=e=>{},o[t]=r,o})))(r);var a=()=>h.map((e=>{if(e[i])throw e[i];return e[t]})),l=new Promise((t=>{(n=()=>t(a)).r=0;var i=e=>e!==o&&!d.has(e)&&(d.add(e),e&&!e.d&&(n.r++,e.push(n)));h.map((t=>t[e](i)))}));return n.r?l:a()}),(e=>(e?c(f[i]=e):l(u),s(o)))),o&&o.d<0&&(o.d=0)},a.d=(e,t)=>{for(var i in t)a.o(t,i)&&!a.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a(485)})(); \ No newline at end of file diff --git a/src/Loader/Optimized/bpmxConverter.ts b/src/Loader/Optimized/bpmxConverter.ts index c6d6af4..eb95ab0 100644 --- a/src/Loader/Optimized/bpmxConverter.ts +++ b/src/Loader/Optimized/bpmxConverter.ts @@ -491,13 +491,24 @@ export class BpmxConverter implements ILogger { const externalParentTransform = boneMetadata.externalParentTransform; const ik = boneMetadata.ik; // remapped later - let flag = (boneMetadata.flag ?? 0) & - (!Array.isArray(tailPosition) ? 0 : ~PmxObject.Bone.Flag.UseBoneIndexAsTailPosition) & - (appendTransform ? 0 : (~PmxObject.Bone.Flag.HasAppendRotate | ~PmxObject.Bone.Flag.HasAppendMove)) & - (axisLimit ? 0 : ~PmxObject.Bone.Flag.HasAxisLimit) & - (localVector ? 0 : ~PmxObject.Bone.Flag.HasLocalVector) & - (externalParentTransform ? 0 : ~PmxObject.Bone.Flag.IsExternalParentTransformed) & - (ik ? 0 : ~PmxObject.Bone.Flag.IsIkEnabled); + let flag = 0; + if (boneMetadata.flag) { + flag = boneMetadata.flag; + } else { + flag = + PmxObject.Bone.Flag.IsRotatable | + PmxObject.Bone.Flag.IsMovable | + PmxObject.Bone.Flag.IsVisible | + PmxObject.Bone.Flag.IsControllable; + } + + flag &= + (!Array.isArray(tailPosition) ? ~0 : ~PmxObject.Bone.Flag.UseBoneIndexAsTailPosition) & + (appendTransform ? ~0 : (~PmxObject.Bone.Flag.HasAppendRotate | ~PmxObject.Bone.Flag.HasAppendMove)) & + (axisLimit ? ~0 : ~PmxObject.Bone.Flag.HasAxisLimit) & + (localVector ? ~0 : ~PmxObject.Bone.Flag.HasLocalVector) & + (externalParentTransform ? ~0 : ~PmxObject.Bone.Flag.IsExternalParentTransformed) & + (ik ? ~0 : ~PmxObject.Bone.Flag.IsIkEnabled); flag |= (!Array.isArray(tailPosition) ? PmxObject.Bone.Flag.UseBoneIndexAsTailPosition : 0) | (appendTransform ? PmxObject.Bone.Flag.HasAppendRotate | PmxObject.Bone.Flag.HasAppendMove : 0) |