const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./depth.vertex-CW17qpql.js","./index-Cwdlo4ih.js","./index-aMLoRFR_.js","./index-B4_9qK8r.css","./bonesDeclaration-VvMhWjky.js","./instancesVertex-XVT5DcYf.js","./morphTargetsVertexDeclaration-3PtfRWQV.js","./clipPlaneVertex-Zg7aFBaq.js","./instancesDeclaration-DMH7shct.js","./morphTargetsVertex-DcY7uT9O.js","./bonesVertex-Cn16K8NY.js","./bakedVertexAnimation-DE01jqsk.js","./depth.fragment-CvX-mM1W.js","./clipPlaneFragment-BKjUM84c.js","./packingFunctions-Blm1CFbB.js"])))=>i.map(i=>d[i]);
import{ShadowGenerator as v}from"./shadowGenerator-Cx60UGrx.js";import{S as R,T as F,b9 as J,aL as se,J as A,E as de,b3 as ce,b2 as ue,b4 as fe,Y as le,b1 as me,$ as _e,a2 as pe,a5 as ge,be as ie,aE as xe,bn as j,O as Me,bE as Se,aA as Ce,V as f,M as T,L as q,aq as ve,av as Ee,bd as be,bF as Re,a as X}from"./index-Cwdlo4ih.js";import{_ as I}from"./index-aMLoRFR_.js";import"./clipPlaneFragment-CQmAI4oM.js";import"./packingFunctions-BGhiI7hH.js";import"./bakedVertexAnimation-CU4K87kt.js";import"./morphTargetsVertex-B1Q5ToCc.js";import"./clipPlaneVertex-BqWHYfPs.js";import"./instancesDeclaration-CBKHSUZu.js";import"./pointCloudVertex-K6njl-Bq.js";import"./svelte/svelte_svelte.js";import"./svelte/svelte_animate.js";import"./svelte/svelte_attachments.js";import"./svelte/svelte_easing.js";import"./svelte/svelte_internal_client.js";import"./svelte/svelte_internal_flags_async.js";import"./svelte/svelte_internal_flags_legacy.js";import"./svelte/svelte_internal_flags_tracing.js";import"./svelte/svelte_internal_server.js";import"./svelte/svelte_legacy.js";import"./svelte/svelte_motion.js";import"./svelte/svelte_reactivity.js";import"./svelte/svelte_reactivity_window.js";import"./svelte/svelte_server.js";import"./svelte/svelte_store.js";import"./svelte/svelte_transition.js";import"./svelte/svelte_events.js";const G="depthPixelShader",re=`#ifdef ALPHATEST
varying vec2 vUV;uniform sampler2D diffuseSampler;
#endif
#include<clipPlaneFragmentDeclaration>
varying float vDepthMetric;
#ifdef PACKED
#include<packingFunctions>
#endif
#ifdef STORE_CAMERASPACE_Z
varying vec4 vViewPos;
#endif
#define CUSTOM_FRAGMENT_DEFINITIONS
void main(void)
{
#include<clipPlaneFragment>
#ifdef ALPHATEST
if (texture2D(diffuseSampler,vUV).a<0.4)
discard;
#endif
#ifdef STORE_CAMERASPACE_Z
#ifdef PACKED
gl_FragColor=pack(vViewPos.z);
#else
gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);
#endif
#else
#ifdef NONLINEARDEPTH
#ifdef PACKED
gl_FragColor=pack(gl_FragCoord.z);
#else
gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);
#endif
#else
#ifdef PACKED
gl_FragColor=pack(vDepthMetric);
#else
gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);
#endif
#endif
#endif
}`;R.ShadersStore[G]||(R.ShadersStore[G]=re);const De={name:G,shader:re},Ae=Object.freeze(Object.defineProperty({__proto__:null,depthPixelShader:De},Symbol.toStringTag,{value:"Module"})),Q="pointCloudVertexDeclaration",Te=`#ifdef POINTSIZE
uniform float pointSize;
#endif
`;R.IncludesShadersStore[Q]||(R.IncludesShadersStore[Q]=Te);const K="depthVertexShader",ne=`attribute vec3 position;
#include<bonesDeclaration>
#include<bakedVertexAnimationDeclaration>
#include<morphTargetsVertexGlobalDeclaration>
#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]
#include<clipPlaneVertexDeclaration>
#include<instancesDeclaration>
uniform mat4 viewProjection;uniform vec2 depthValues;
#if defined(ALPHATEST) || defined(NEED_UV)
varying vec2 vUV;uniform mat4 diffuseMatrix;
#ifdef UV1
attribute vec2 uv;
#endif
#ifdef UV2
attribute vec2 uv2;
#endif
#endif
#ifdef STORE_CAMERASPACE_Z
uniform mat4 view;varying vec4 vViewPos;
#endif
#include<pointCloudVertexDeclaration>
varying float vDepthMetric;
#define CUSTOM_VERTEX_DEFINITIONS
void main(void)
{vec3 positionUpdated=position;
#ifdef UV1
vec2 uvUpdated=uv;
#endif
#ifdef UV2
vec2 uv2Updated=uv2;
#endif
#include<morphTargetsVertexGlobal>
#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]
#include<instancesVertex>
#include<bonesVertex>
#include<bakedVertexAnimation>
vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);
#include<clipPlaneVertex>
gl_Position=viewProjection*worldPos;
#ifdef STORE_CAMERASPACE_Z
vViewPos=view*worldPos;
#else
#ifdef USE_REVERSE_DEPTHBUFFER
vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));
#else
vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));
#endif
#endif
#if defined(ALPHATEST) || defined(BASIC_RENDER)
#ifdef UV1
vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));
#endif
#ifdef UV2
vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0));
#endif
#endif
#include<pointCloudVertex>
}
`;R.ShadersStore[K]||(R.ShadersStore[K]=ne);const Pe={name:K,shader:ne},we=Object.freeze(Object.defineProperty({__proto__:null,depthVertexShader:Pe},Symbol.toStringTag,{value:"Module"}));class B{get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=F.TRILINEAR_SAMPLINGMODE,n=!1,o,h){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=t===0,this.isPacked?this.clearColor=new J(1,1,1,1):this.clearColor=new J(n?0:1,0,0,1),this._initShaderSourceAsync(),B._SceneComponentInitialization(this._scene);const d=e.getEngine();this._camera=i,r!==F.NEAREST_SAMPLINGMODE&&(t===1&&!d._caps.textureFloatLinearFiltering&&(r=F.NEAREST_SAMPLINGMODE),t===2&&!d._caps.textureHalfFloatLinearFiltering&&(r=F.NEAREST_SAMPLINGMODE));const c=this.isPacked||!d._features.supportExtendedTextureFormats?5:6;this._depthMap=h??new se(o??"DepthRenderer",{width:d.getRenderWidth(),height:d.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,c),this._depthMap.wrapU=F.CLAMP_ADDRESSMODE,this._depthMap.wrapV=F.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(u=>{u.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{d._enableGPUDebugMarkers&&(d.restoreDefaultFramebuffer(),d._debugPushGroup?.("Depth renderer"))}),this._depthMap.onAfterUnbindObservable.add(()=>{d._enableGPUDebugMarkers&&d._debugPopGroup?.()}),this._depthMap.customIsReadyFunction=(u,p,l)=>{if((l||p===0)&&u.subMeshes)for(let _=0;_<u.subMeshes.length;++_){const a=u.subMeshes[_],M=a.getRenderingMesh(),P=M._getInstancesRenderList(a._id,!!a.getReplacementMesh()),E=d.getCaps().instancedArrays&&(P.visibleInstances[a._id]!==null&&P.visibleInstances[a._id]!==void 0||M.hasThinInstances);if(!this.isReady(a,E))return!1}return!0};const g=u=>{const p=u.getRenderingMesh(),l=u.getEffectiveMesh(),_=this._scene,a=_.getEngine(),M=u.getMaterial();if(l._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!M||l.infiniteDistance||M.disableDepthWrite||u.verticesCount===0||u._renderId===_.getRenderId())return;const P=l._getWorldMatrixDeterminant()<0;let E=M._getEffectiveOrientation(p);P&&(E=E===0?1:0);const k=E===0;a.setState(M.backFaceCulling,0,!1,k,this.reverseCulling?!M.cullBackFaces:M.cullBackFaces);const y=p._getInstancesRenderList(u._id,!!u.getReplacementMesh());if(y.mustReturn)return;const N=a.getCaps().instancedArrays&&(y.visibleInstances[u._id]!==null&&y.visibleInstances[u._id]!==void 0||p.hasThinInstances),O=this._camera||_.activeCamera;if(this.isReady(u,N)&&O){u._renderId=_.getRenderId();let D=l._internalAbstractMeshDataInfo._materialForRenderPass?.[a.currentRenderPassId];if(D===void 0&&l.getClassName()==="GaussianSplattingMesh"&&(D=l.material.makeDepthRenderingMaterial(this._scene,this._shaderLanguage),this.setMaterialForRendering(l,D),!D.isReady()))return;let L=u._getDrawWrapper();!L&&D&&(L=D._getDrawWrapper());const he=O.mode===me.ORTHOGRAPHIC_CAMERA;if(!L)return;const C=L.effect;a.enableEffect(L),N||p._bind(u,C,M.fillMode),D?D.bindForSubMesh(l.getWorldMatrix(),l,u):(C.setMatrix("viewProjection",_.getTransformMatrix()),C.setMatrix("world",l.getWorldMatrix()),this._storeCameraSpaceZ&&C.setMatrix("view",_.getViewMatrix()));let W,H;if(he?(W=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,H=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(W=a.useReverseDepthBuffer&&a.isNDCHalfZRange?O.minZ:a.isNDCHalfZRange?0:O.minZ,H=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:O.maxZ),C.setFloat2("depthValues",W,W+H),!D){if(M.needAlphaTestingForMesh(l)){const V=M.getAlphaTestTexture();V&&(C.setTexture("diffuseSampler",V),C.setMatrix("diffuseMatrix",V.getTextureMatrix()))}_e(p,C),pe(C,M,_),ge(p,C),p.morphTargetManager&&p.morphTargetManager.isUsingTextureForTargets&&p.morphTargetManager._bind(C);const U=u.getMesh().bakedVertexAnimationManager;U&&U.isEnabled&&U.bind(C,N),M.pointsCloud&&C.setFloat("pointSize",M.pointSize)}p._processRendering(l,u,C,M.fillMode,y,N,(U,V)=>C.setMatrix("world",V))}};this._depthMap.customRenderFunction=(u,p,l,_)=>{let a;if(_.length)for(a=0;a<_.length;a++)g(_.data[a]);for(a=0;a<u.length;a++)g(u.data[a]);for(a=0;a<p.length;a++)g(p.data[a]);if(this.forceDepthWriteTransparentMeshes)for(a=0;a<l.length;a++)g(l.data[a]);else for(a=0;a<l.length;a++)l.data[a].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}async _initShaderSourceAsync(e=!1){this._scene.getEngine().isWebGPU&&!e&&!B.ForceGLSL?(this._shaderLanguage=1,await Promise.all([I(()=>import("./depth.vertex-CW17qpql.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11]),import.meta.url),I(()=>import("./depth.fragment-CvX-mM1W.js"),__vite__mapDeps([12,1,2,3,13,14]),import.meta.url)])):await Promise.all([I(()=>Promise.resolve().then(()=>we),void 0,import.meta.url),I(()=>Promise.resolve().then(()=>Ae),void 0,import.meta.url)]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;const i=this._scene.getEngine(),s=e.getMesh(),r=s.getScene(),n=s._internalAbstractMeshDataInfo._materialForRenderPass?.[i.currentRenderPassId];if(n)return n.isReadyForSubMesh(s,e,t);const o=e.getMaterial();if(!o||o.disableDepthWrite)return!1;const h=[],d=[A.PositionKind];let c=!1,g=!1;const u=!1;o.needAlphaTestingForMesh(s)&&o.getAlphaTestTexture()&&(h.push("#define ALPHATEST"),s.isVerticesDataPresent(A.UVKind)&&(d.push(A.UVKind),h.push("#define UV1"),c=!0),s.isVerticesDataPresent(A.UV2Kind)&&(d.push(A.UV2Kind),h.push("#define UV2"),g=!0));const p=new de;if(s.useBones&&s.computeBonesUsingShaders&&s.skeleton){d.push(A.MatricesIndicesKind),d.push(A.MatricesWeightsKind),s.numBoneInfluencers>4&&(d.push(A.MatricesIndicesExtraKind),d.push(A.MatricesWeightsExtraKind)),h.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),s.numBoneInfluencers>0&&p.addCPUSkinningFallback(0,s);const E=s.skeleton;E.isUsingTextureForMatrices?h.push("#define BONETEXTURE"):h.push("#define BonesPerMesh "+(E.bones.length+1))}else h.push("#define NUM_BONE_INFLUENCERS 0");const l=s.morphTargetManager?ce(s.morphTargetManager,h,d,s,!0,!1,!1,c,g,u):0;o.pointsCloud&&h.push("#define POINTSIZE"),t&&(h.push("#define INSTANCES"),ue(d),e.getRenderingMesh().hasThinInstances&&h.push("#define THIN_INSTANCES"));const _=s.bakedVertexAnimationManager;_&&_.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&d.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&h.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&h.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&h.push("#define PACKED"),fe(o,r,h);const a=e._getDrawWrapper(void 0,!0),M=a.defines,P=h.join(`
`);if(M!==P){const E=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],k=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];le(E),a.setEffect(i.createEffect("depth",{attributes:d,uniformsNames:E,uniformBuffersNames:[],samplers:k,defines:P,fallbacks:p,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:l},shaderLanguage:this._shaderLanguage},i),P)}return a.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]}}}B.ForceGLSL=!1;B._SceneComponentInitialization=S=>{throw ie("DepthRendererSceneComponent")};var ee;(function(S){S[S.NormalizedViewDepth=0]="NormalizedViewDepth",S[S.ViewDepth=1]="ViewDepth",S[S.ScreenDepth=2]="ScreenDepth"})(ee||(ee={}));class w extends xe{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(I(()=>Promise.resolve().then(()=>Ue),void 0,import.meta.url))):t.push(I(()=>Promise.resolve().then(()=>Oe),void 0,import.meta.url))}constructor(e,t=null,i="",s){super({...s,name:e,engine:t||j.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:w.FragmentUrl,uniforms:w.Uniforms,defines:i}),this.textureWidth=0,this.textureHeight=0}bind(e=!1){super.bind(e);const t=this.drawWrapper.effect;this.textureWidth===1||this.textureHeight===1?t.setInt2("texSize",this.textureWidth,this.textureHeight):t.setFloat2("texSize",this.textureWidth,this.textureHeight)}}w.FragmentUrl="minmaxRedux";w.Uniforms=["texSize"];const Fe=new Float32Array(4),ze=new Uint8Array(4),b={min:0,max:0};class Ie{get depthRedux(){return this._depthRedux}set depthRedux(e){this._depthRedux!==e&&(this._depthRedux=e,this._recreatePostProcesses())}get textureWidth(){return this._textureWidth}get textureHeight(){return this._textureHeight}constructor(e,t=!0){this.onAfterReductionPerformed=new Me,this._textureWidth=0,this._textureHeight=0,this._scene=e,this._depthRedux=t,this.reductionSteps=[]}setTextureDimensions(e,t,i=0){return e===this._textureWidth&&t===this._textureHeight&&i===this._depthTextureType?!1:(this._textureWidth=e,this._textureHeight=t,this._depthTextureType=i,this._recreatePostProcesses(),!0)}readMinMax(e){const t=e.type===j.TEXTURETYPE_FLOAT||e.type===j.TEXTURETYPE_HALF_FLOAT,i=t?Fe:ze;this._scene.getEngine()._readTexturePixels(e,1,1,-1,0,i,!1),b.min=i[0],b.max=i[1],t||(b.min=b.min/255,b.max=b.max/255),b.min>=b.max&&(b.min=0,b.max=1),this.onAfterReductionPerformed.notifyObservers(b)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._textureWidth=0,this._textureHeight=0);for(let t=0;t<this.reductionSteps.length;++t)this.reductionSteps[t].dispose();this.reductionSteps.length=0}_recreatePostProcesses(){this.dispose(!1);const e=this._scene;let t=this.textureWidth,i=this.textureHeight;const s=new w("Initial reduction phase",e.getEngine(),"#define INITIAL"+(this._depthRedux?`
#define DEPTH_REDUX`:"")+(this._depthTextureType===1?`
#define VIEW_DEPTH`:""));s.textureWidth=t,s.textureHeight=i,this.reductionSteps.push(s);let r=1;for(;t>1||i>1;){t=Math.max(Math.round(t/2),1),i=Math.max(Math.round(i/2),1);const n=new w("Reduction phase "+r,e.getEngine(),"#define "+(t==1&&i==1?"LAST":t==1||i==1?"ONEBEFORELAST":"MAIN"));n.textureWidth=t,n.textureHeight=i,this.reductionSteps.push(n),r++}}}const $="minmaxReduxPixelShader",ae=`varying vec2 vUV;uniform sampler2D textureSampler;
#if defined(INITIAL)
uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(textureSampler,coord,0).r;float f2=texelFetch(textureSampler,coord+ivec2(1,0),0).r;float f3=texelFetch(textureSampler,coord+ivec2(1,1),0).r;float f4=texelFetch(textureSampler,coord+ivec2(0,1),0).r;
#ifdef DEPTH_REDUX
#ifdef VIEW_DEPTH
float minz=3.4e38;if (f1 != 0.0) { minz=f1; }
if (f2 != 0.0) { minz=min(minz,f2); }
if (f3 != 0.0) { minz=min(minz,f3); }
if (f4 != 0.0) { minz=min(minz,f4); }
float maxz=max(max(max(f1,f2),f3),f4);
#else
float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#endif
#else
float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(f1,f2),f3),f4);
#endif
glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(MAIN)
uniform vec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(ONEBEFORELAST)
uniform ivec2 texSize;void main(void)
{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}
#elif defined(LAST)
void main(void)
{glFragColor=vec4(0.);if (true) { 
discard;}}
#endif
`;R.ShadersStore[$]||(R.ShadersStore[$]=ae);const Be={name:$,shader:ae},Oe=Object.freeze(Object.defineProperty({__proto__:null,minmaxReduxPixelShader:Be},Symbol.toStringTag,{value:"Module"})),Y="minmaxReduxPixelShader",oe=`varying vUV: vec2f;var textureSampler: texture_2d<f32>;
#if defined(INITIAL)
uniform texSize: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).r;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).r;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).r;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).r;
#ifdef DEPTH_REDUX
#ifdef VIEW_DEPTH
var minz=3.4e38;if (f1 != 0.0) { minz=f1; }
if (f2 != 0.0) { minz=min(minz,f2); }
if (f3 != 0.0) { minz=min(minz,f3); }
if (f4 != 0.0) { minz=min(minz,f4); }
let maxz=max(max(max(f1,f2),f3),f4);
#else
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);
#endif
#else
let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(f1,f2),f3),f4);
#endif
fragmentOutputs.color=vec4f(minz,maxz,0.,0.);}
#elif defined(MAIN)
uniform texSize: vec2f;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).rg;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).rg;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).rg;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
#elif defined(ONEBEFORELAST)
uniform texSize: vec2i;@fragment
fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*vec2f(uniforms.texSize-1));let f1=textureLoad(textureSampler,coord % uniforms.texSize,0).rg;let f2=textureLoad(textureSampler,(coord+vec2i(1,0)) % uniforms.texSize,0).rg;let f3=textureLoad(textureSampler,(coord+vec2i(1,1)) % uniforms.texSize,0).rg;let f4=textureLoad(textureSampler,(coord+vec2i(0,1)) % uniforms.texSize,0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);}
#elif defined(LAST)
@fragment
fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(0.);if (true) { 
discard;}}
#endif
`;R.ShadersStoreWGSL[Y]||(R.ShadersStoreWGSL[Y]=oe);const Le={name:Y,shader:oe},Ue=Object.freeze(Object.defineProperty({__proto__:null,minmaxReduxPixelShaderWGSL:Le},Symbol.toStringTag,{value:"Module"}));class Ve{get onAfterReductionPerformed(){return this._thinMinMaxReducer.onAfterReductionPerformed}constructor(e){this._onAfterUnbindObserver=null,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Se(e.getScene()),this._thinMinMaxReducer=new Ie(e.getScene()),this._reductionSteps=[],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&&(this._thinMinMaxReducer.depthRedux=t,this.deactivate(),this._sourceTexture=e,this._forceFullscreenViewport=s,this._thinMinMaxReducer.setTextureDimensions(e.getRenderWidth(),e.getRenderHeight()))){this._disposePostProcesses();const r=this._thinMinMaxReducer.reductionSteps;for(let n=0;n<r.length;++n){const o=r[n],h=new Ce(o.name,w.FragmentUrl,{effectWrapper:o,samplingMode:1,engine:this._camera.getScene().getEngine(),textureType:i,textureFormat:7,size:{width:o.textureWidth,height:o.textureHeight}});this._reductionSteps.push(h),h.autoClear=!1,h.forceFullscreenViewport=s,n===0&&(h.externalTextureSamplerBinding=!0,h.onApplyObservable.add(d=>{d.setTexture("textureSampler",this._sourceTexture)})),n===r.length-1&&this._reductionSteps[n-1].onAfterRenderObservable.add(()=>{this._thinMinMaxReducer.readMinMax(h.inputTexture.texture)})}}}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"),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport,0,0,!0,this._reductionSteps.length-1),e.unBindFramebuffer(this._reductionSteps[this._reductionSteps.length-1].inputTexture,!1),e._debugPopGroup?.()}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=void 0,this._disposePostProcesses(),this._postProcessManager.dispose(),this._postProcessManager=void 0,this._thinMinMaxReducer.dispose(),this._thinMinMaxReducer=void 0,this._sourceTexture=null)}_disposePostProcesses(){for(let e=0;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps.length=0}}class ye extends Ve{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){const s=this._camera.getScene();this._depthRenderer&&(delete s._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),e===null&&(s._depthRenderer||(s._depthRenderer={}),this._depthRendererId="minmax_"+this._camera.id,e=this._depthRenderer=new B(s,t,this._camera,!1,1,!1,`DepthRenderer ${this._depthRendererId}`),e.enabled=!1,s._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,s=!0){super.setSourceTexture(e,t,i,s)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){super.dispose(e),this._depthRenderer&&e&&(this._depthRenderer.dispose(),this._depthRenderer=null)}}const te=f.Up(),Ne=f.Zero(),m=new f,z=new f,Z=new T;class x extends v{_validateFilter(e){return e===v.FILTER_NONE||e===v.FILTER_PCF||e===v.FILTER_PCSS?e:(q.Error('Unsupported filter "'+e+'"!'),v.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){e=Math.min(Math.max(e,x.MIN_CASCADES_COUNT),x.MAX_CASCADES_COUNT),e!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),!this._freezeShadowCastersBoundingInfoObservable&&!e&&(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._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;t<e.length;t++){const i=e[t];if(!i)continue;const s=i.getBoundingInfo(),r=s.boundingBox;this._scbiMin.minimizeInPlace(r.minimumWorld),this._scbiMax.maximizeInPlace(r.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){this._minDistance===e&&this._maxDistance===t||(e>t&&(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 x.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){const t=this._getCamera();if(!t){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<t.minZ||e>t.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){const t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new ye(t),this._depthReducer.onAfterReductionPerformed.add(i=>{let s=i.min,r=i.max;s>=r&&(s=0,r=1),(s!=this._minDistance||r!=this._maxDistance)&&this.setMinMaxDistance(s,r)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){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=this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+r*s,h=t+n*s,d=h-o,c=h/o;for(let g=0;g<this._cascades.length;++g){const u=(g+1)/this._numCascades,p=o*c**u,l=o+d*u,_=this._lambda*(p-l)+l;this._cascades[g].prevBreakDistance=g===0?r:this._cascades[g-1].breakDistance,this._cascades[g].breakDistance=(_-t)/s,this._viewSpaceFrustumsZ[g]=_,this._frustumLengths[g]=(this._cascades[g].breakDistance-this._cascades[g].prevBreakDistance)*s}this._breaksAreDirty=!1}_computeMatrices(){const e=this._scene;if(!this._getCamera())return;f.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),Math.abs(f.Dot(this._lightDirection,f.Up()))===1&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);const i=e.getEngine().useReverseDepthBuffer;for(let s=0;s<this._numCascades;++s){this._computeFrustumInWorldSpace(s),this._computeCascadeFrustum(s),this._cascadeMaxExtents[s].subtractToRef(this._cascadeMinExtents[s],m),this._frustumCenter[s].addToRef(this._lightDirection.scale(this._cascadeMinExtents[s].z),this._shadowCameraPos[s]),T.LookAtLHToRef(this._shadowCameraPos[s],this._frustumCenter[s],te,this._viewMatrices[s]);let r=0,n=m.z;const o=this._shadowCastersBoundingInfo;o.update(this._viewMatrices[s]);const h=o.boundingBox.minimumWorld.z,d=o.boundingBox.maximumWorld.z;h>n||(!this._depthClamp||this.filter===v.FILTER_PCSS?(r=Math.min(r,h),this.filter!==v.FILTER_PCSS&&(n=Math.min(n,d))):(n=Math.min(n,d),r=Math.max(r,h),n=Math.max(r+1,n))),T.OrthoOffCenterLHToRef(this._cascadeMinExtents[s].x,this._cascadeMaxExtents[s].x,this._cascadeMinExtents[s].y,this._cascadeMaxExtents[s].y,i?n:r,i?r:n,this._projectionMatrices[s],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[s].z=r,this._cascadeMaxExtents[s].z=n,this._viewMatrices[s].multiplyToRef(this._projectionMatrices[s],this._transformMatrices[s]),f.TransformCoordinatesToRef(Ne,this._transformMatrices[s],m),m.scaleInPlace(this._mapSize/2),z.copyFromFloats(Math.round(m.x),Math.round(m.y),Math.round(m.z)),z.subtractInPlace(m).scaleInPlace(2/this._mapSize),T.TranslationToRef(z.x,z.y,0,Z),this._projectionMatrices[s].multiplyToRef(Z,this._projectionMatrices[s]),this._viewMatrices[s].multiplyToRef(this._projectionMatrices[s],this._transformMatrices[s]),this._transformMatrices[s].copyToArray(this._transformMatricesAsArray,s*16)}}_computeFrustumInWorldSpace(e){const t=this._getCamera();if(!t)return;const i=this._cascades[e].prevBreakDistance,s=this._cascades[e].breakDistance,r=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();const n=t.maxZ===0,o=t.maxZ;n&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));const h=T.Invert(t.getTransformationMatrix());n&&(t.maxZ=o,t.getProjectionMatrix(!0));const d=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let c=0;c<x._FrustumCornersNdcSpace.length;++c)m.copyFrom(x._FrustumCornersNdcSpace[(c+d)%x._FrustumCornersNdcSpace.length]),r&&m.z===-1&&(m.z=0),f.TransformCoordinatesToRef(m,h,this._frustumCornersWorldSpace[e][c]);for(let c=0;c<x._FrustumCornersNdcSpace.length/2;++c)m.copyFrom(this._frustumCornersWorldSpace[e][c+4]).subtractInPlace(this._frustumCornersWorldSpace[e][c]),z.copyFrom(m).scaleInPlace(i),m.scaleInPlace(s),m.addInPlace(this._frustumCornersWorldSpace[e][c]),this._frustumCornersWorldSpace[e][c+4].copyFrom(m),this._frustumCornersWorldSpace[e][c].addInPlace(z)}_computeCascadeFrustum(e){if(this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0),!!this._getCamera()){for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][i]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let i=0;for(let s=0;s<this._frustumCornersWorldSpace[e].length;++s){const r=this._frustumCornersWorldSpace[e][s].subtractToRef(this._frustumCenter[e],m).length();i=Math.max(i,r)}i=Math.ceil(i*16)/16,this._cascadeMaxExtents[e].copyFromFloats(i,i,i),this._cascadeMinExtents[e].copyFromFloats(-i,-i,-i)}else{const i=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,m),T.LookAtLHToRef(i,m,te,Z);for(let s=0;s<this._frustumCornersWorldSpace[e].length;++s)f.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][s],Z,m),this._cascadeMinExtents[e].minimizeInPlace(m),this._cascadeMaxExtents[e].maximizeInPlace(m)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`))}static get IsSupported(){const e=ve.LastCreatedEngine;return e?e._features.supportCSM:!1}constructor(e,t,i,s,r=!0){if(!x.IsSupported){q.Error("CascadedShadowMap is not supported by the current engine.");return}super(e,t,i,s,r),this.usePercentageCloserFiltering=!0}_initializeGenerator(){this.penumbraDarkness=this.penumbraDarkness??1,this._numCascades=this._numCascades??x.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=this.stabilizeCascades??!1,this._freezeShadowCastersBoundingInfoObservable=this._freezeShadowCastersBoundingInfoObservable??null,this.freezeShadowCastersBoundingInfo=this.freezeShadowCastersBoundingInfo??!1,this._scbiMin=this._scbiMin??new f(0,0,0),this._scbiMax=this._scbiMax??new f(0,0,0),this._shadowCastersBoundingInfo=this._shadowCastersBoundingInfo??new Ee(new f(0,0,0),new f(0,0,0)),this._breaksAreDirty=this._breaksAreDirty??!0,this._minDistance=this._minDistance??0,this._maxDistance=this._maxDistance??1,this._currentLayer=this._currentLayer??0,this._shadowMaxZ=this._shadowMaxZ??this._getCamera()?.maxZ??1e4,this._debug=this._debug??!1,this._depthClamp=this._depthClamp??!0,this._cascadeBlendPercentage=this._cascadeBlendPercentage??.1,this._lambda=this._lambda??.5,this._autoCalcDepthBounds=this._autoCalcDepthBounds??!1,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){const e=this._scene.getEngine();this._shadowMap?.dispose();const t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new se(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForCSMShadowGenerator-${this._light.name}`),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(super._initializeShadowMap(),this._shadowMap===null)return;this._transformMatricesAsArray=new Float32Array(this._numCascades*16),this._tempTransformMatricesAsArray=new Float32Array(this._numCascades*16),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(this._numCascades*2),this._depthCorrection=new Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let t=0;t<this._numCascades;++t){this._cascades[t]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[t]=T.Zero(),this._projectionMatrices[t]=T.Zero(),this._transformMatrices[t]=T.Zero(),this._cascadeMinExtents[t]=new f,this._cascadeMaxExtents[t]=new f,this._frustumCenter[t]=new f,this._shadowCameraPos[t]=new f,this._frustumCornersWorldSpace[t]=new Array(x._FrustumCornersNdcSpace.length);for(let i=0;i<x._FrustumCornersNdcSpace.length;++i)this._frustumCornersWorldSpace[t][i]=new f}const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===v.FILTER_PCF&&e.setColorWrite(!1),be.eyeAtCamera=!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._enableGPUDebugMarkers&&(e.restoreDefaultFramebuffer(),e._debugPushGroup?.(`Cascaded shadow map generation for pass id ${e.currentRenderPassId}`)),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!==v.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light,s=this._scene;if(!s.shadowsEnabled||!i.shadowEnabled)return;const r=this._getCamera();if(!r)return;const n=this.getShadowMap();if(!n)return;const o=n.getSize().width,h=this._transformMatricesAsArray,d=s.floatingOriginMode?Re(this._scene.floatingOriginOffset,this._viewMatrices,this._projectionMatrices,this._numCascades,this._tempTransformMatricesAsArray):h;if(t.setMatrices("lightMatrix"+e,d),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===v.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===v.FILTER_PCSS){for(let c=0;c<this._numCascades;++c)this._lightSizeUVCorrection[c*2+0]=c===0?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[c].x-this._cascadeMinExtents[c].x),this._lightSizeUVCorrection[c*2+1]=c===0?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[c].y-this._cascadeMinExtents[c].y),this._depthCorrection[c]=c===0?1:(this._cascadeMaxExtents[c].z-this._cascadeMinExtents[c].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/o,this._contactHardeningLightSizeUVRatio*o,this.frustumEdgeFalloff,e)}else t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){const e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){const s=t.renderList[i];e.renderList.push(s.id)}return e}static Parse(e,t){const i=v.Parse(e,t,(s,r,n)=>new x(s,r,void 0,n));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}x._FrustumCornersNdcSpace=[new f(-1,1,-1),new f(1,1,-1),new f(1,-1,-1),new f(-1,-1,-1),new f(-1,1,1),new f(1,1,1),new f(1,-1,1),new f(-1,-1,1)];x.CLASSNAME="CascadedShadowGenerator";x.DEFAULT_CASCADES_COUNT=4;x.MIN_CASCADES_COUNT=2;x.MAX_CASCADES_COUNT=4;x._SceneComponentInitialization=S=>{throw ie("ShadowGeneratorSceneComponent")};class We{constructor(e){this.name=X.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(X.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];const t=this.scene.lights;for(const i of t){if(i.doNotSerialize)continue;const s=i.getShadowGenerators();if(s){const r=s.values();for(let n=r.next();n.done!==!0;n=r.next()){const o=n.value;o.doNotSerialize||e.shadowGenerators.push(o.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){const t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){const s=t.lights[i],r=s.getShadowGenerators();if(s.isEnabled()&&s.shadowEnabled&&r){const n=r.values();for(let o=n.next();o.done!==!0;o=n.next()){const d=o.value.getShadowMap();t.textures.indexOf(d)!==-1&&e.push(d)}}}}}v._SceneComponentInitialization=S=>{let e=S._getComponent(X.NAME_SHADOWGENERATOR);e||(e=new We(S),S._addComponent(e))};export{We as ShadowGeneratorSceneComponent};
