UNPKG

@babylonjs/viewer

Version:

The Babylon Viewer aims to simplify a specific but common Babylon.js use case: loading, viewing, and interacting with a 3D model.

1,149 lines (1,146 loc) 93.5 kB
import { E as EffectWrapper, k as Engine, P as PostProcess, T as Texture, C as Constants, Y as SerializationHelper, u as __decorate, a5 as serializeAsVector2, v as serialize, R as RegisterClass, O as Observable, V as Vector3, M as Matrix, h as RenderTargetTexture, j as Color4, a6 as RenderingManager, a7 as Vector2, J as DrawWrapper, a8 as Light, s as BindMorphTargetParameters, r as BindClipPlane, q as BindSceneUniformBuffer, m as VertexBuffer, $ as EffectFallbacks, n as PrepareDefinesAndAttributesForMorphTargets, p as PrepareStringDefinesForClipPlanes, o as PushAttributesForInstances, A as AddClipPlaneUniforms, _ as _WarnImport } from './index-FzOfPXLV.esm.js'; /** * Post process used to apply a blur effect */ class ThinBlurPostProcess extends EffectWrapper { _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.all([import('./kernelBlur.fragment-C1vYcaMm.esm.js'), import('./kernelBlur.vertex-D_oAZPE6.esm.js')])); } else { list.push(Promise.all([import('./kernelBlur.fragment-BmXuxF74.esm.js'), import('./kernelBlur.vertex-C4xXgHWu.esm.js')])); } } /** * Constructs a new blur post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param direction Direction in which to apply the blur * @param kernel Kernel size of the blur * @param options Options to configure the effect */ constructor(name, engine = null, direction, kernel, options) { const blockCompilationFinal = !!options?.blockCompilation; super({ ...options, name, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: ThinBlurPostProcess.FragmentUrl, uniforms: ThinBlurPostProcess.Uniforms, samplers: ThinBlurPostProcess.Samplers, vertexUrl: ThinBlurPostProcess.VertexUrl, blockCompilation: true, }); this._packedFloat = false; this._staticDefines = ""; /** * Width of the texture to apply the blur on */ this.textureWidth = 0; /** * Height of the texture to apply the blur on */ this.textureHeight = 0; this._staticDefines = options ? (Array.isArray(options.defines) ? options.defines.join("\n") : options.defines || "") : ""; this.options.blockCompilation = blockCompilationFinal; if (direction !== undefined) { this.direction = direction; } if (kernel !== undefined) { this.kernel = kernel; } } /** * Sets the length in pixels of the blur sample region */ set kernel(v) { if (this._idealKernel === v) { return; } v = Math.max(v, 1); this._idealKernel = v; this._kernel = this._nearestBestKernel(v); if (!this.options.blockCompilation) { this._updateParameters(); } } /** * Gets the length in pixels of the blur sample region */ get kernel() { return this._idealKernel; } /** * Sets whether or not the blur needs to unpack/repack floats */ set packedFloat(v) { if (this._packedFloat === v) { return; } this._packedFloat = v; if (!this.options.blockCompilation) { this._updateParameters(); } } /** * Gets whether or not the blur is unpacking/repacking floats */ get packedFloat() { return this._packedFloat; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); this._drawWrapper.effect.setFloat2("delta", (1 / this.textureWidth) * this.direction.x, (1 / this.textureHeight) * this.direction.y); } /** @internal */ _updateParameters(onCompiled, onError) { // Generate sampling offsets and weights const n = this._kernel; const centerIndex = (n - 1) / 2; // Generate Gaussian sampling weights over kernel let offsets = []; let weights = []; let totalWeight = 0; for (let i = 0; i < n; i++) { const u = i / (n - 1); const w = this._gaussianWeight(u * 2.0 - 1); offsets[i] = i - centerIndex; weights[i] = w; totalWeight += w; } // Normalize weights for (let i = 0; i < weights.length; i++) { weights[i] /= totalWeight; } // Optimize: combine samples to take advantage of hardware linear sampling // Walk from left to center, combining pairs (symmetrically) const linearSamplingWeights = []; const linearSamplingOffsets = []; const linearSamplingMap = []; for (let i = 0; i <= centerIndex; i += 2) { const j = Math.min(i + 1, Math.floor(centerIndex)); const singleCenterSample = i === j; if (singleCenterSample) { linearSamplingMap.push({ o: offsets[i], w: weights[i] }); } else { const sharedCell = j === centerIndex; const weightLinear = weights[i] + weights[j] * (sharedCell ? 0.5 : 1); const offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]); if (offsetLinear === 0) { linearSamplingMap.push({ o: offsets[i], w: weights[i] }); linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] }); } else { linearSamplingMap.push({ o: offsetLinear, w: weightLinear }); linearSamplingMap.push({ o: -offsetLinear, w: weightLinear }); } } } for (let i = 0; i < linearSamplingMap.length; i++) { linearSamplingOffsets[i] = linearSamplingMap[i].o; linearSamplingWeights[i] = linearSamplingMap[i].w; } // Replace with optimized offsets = linearSamplingOffsets; weights = linearSamplingWeights; // Generate shaders const maxVaryingRows = this.options.engine.getCaps().maxVaryingVectors - (this.options.shaderLanguage === 1 /* ShaderLanguage.WGSL */ ? 1 : 0); // Because of the additional builtins const freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1; // Because of sampleCenter let varyingCount = Math.min(offsets.length, freeVaryingVec2); let defines = ""; defines += this._staticDefines; // The DOF fragment should ignore the center pixel when looping as it is handled manually in the fragment shader. if (this._staticDefines.indexOf("DOF") != -1) { defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])}\n`; varyingCount--; } for (let i = 0; i < varyingCount; i++) { defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])}\n`; defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])}\n`; } let depCount = 0; for (let i = freeVaryingVec2; i < offsets.length; i++) { defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])}\n`; defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])}\n`; depCount++; } if (this.packedFloat) { defines += `#define PACKEDFLOAT 1`; } this.options.blockCompilation = false; this.updateEffect(defines, null, null, { varyingCount: varyingCount, depCount: depCount, }, onCompiled, onError); } /** * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard. * The gaps between physical kernels are compensated for in the weighting of the samples * @param idealKernel Ideal blur kernel. * @returns Nearest best kernel. */ _nearestBestKernel(idealKernel) { const v = Math.round(idealKernel); for (const k of [v, v - 1, v + 1, v - 2, v + 2]) { if (k % 2 !== 0 && Math.floor(k / 2) % 2 === 0 && k > 0) { return Math.max(k, 3); } } return Math.max(v, 3); } /** * Calculates the value of a Gaussian distribution with sigma 3 at a given point. * @param x The point on the Gaussian distribution to sample. * @returns the value of the Gaussian function at x. */ _gaussianWeight(x) { //reference: Engines/ImageProcessingBlur.cpp #dcc760 // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1], // so we truncate at three standard deviations by setting stddev (sigma) to 1/3. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is // truncated at around 1.3% of peak strength. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size const sigma = 1 / 3; const denominator = Math.sqrt(2.0 * Math.PI) * sigma; const exponent = -((x * x) / (2.0 * sigma * sigma)); const weight = (1.0 / denominator) * Math.exp(exponent); return weight; } /** * Generates a string that can be used as a floating point number in GLSL. * @param x Value to print. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s). * @returns GLSL float string. */ _glslFloat(x, decimalFigures = 8) { return x.toFixed(decimalFigures).replace(/0+$/, ""); } } /** * The vertex shader url */ ThinBlurPostProcess.VertexUrl = "kernelBlur"; /** * The fragment shader url */ ThinBlurPostProcess.FragmentUrl = "kernelBlur"; /** * The list of uniforms used by the effect */ ThinBlurPostProcess.Uniforms = ["delta", "direction"]; /** * The list of samplers used by the effect */ ThinBlurPostProcess.Samplers = ["circleOfConfusionSampler"]; /** * The Blur Post Process which blurs an image based on a kernel and direction. * Can be used twice in x and y directions to perform a gaussian blur in two passes. */ class BlurPostProcess extends PostProcess { /** The direction in which to blur the image. */ get direction() { return this._effectWrapper.direction; } set direction(value) { this._effectWrapper.direction = value; } /** * Sets the length in pixels of the blur sample region */ set kernel(v) { this._effectWrapper.kernel = v; } /** * Gets the length in pixels of the blur sample region */ get kernel() { return this._effectWrapper.kernel; } /** * Sets whether or not the blur needs to unpack/repack floats */ set packedFloat(v) { this._effectWrapper.packedFloat = v; } /** * Gets whether or not the blur is unpacking/repacking floats */ get packedFloat() { return this._effectWrapper.packedFloat; } /** * Gets a string identifying the name of the class * @returns "BlurPostProcess" string */ getClassName() { return "BlurPostProcess"; } /** * Creates a new instance BlurPostProcess * @param name The name of the effect. * @param direction The direction in which to blur the image. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) * @param camera The camera to apply the render pass to. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) * @param engine The engine which the post process will be applied. (default: current engine) * @param reusable If the post process can be reused on the same frame. (default: false) * @param textureType Type of textures used when performing the post process. (default: 0) * @param defines * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) */ constructor(name, direction, kernel, options, camera = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = Constants.TEXTURETYPE_UNSIGNED_BYTE, defines = "", blockCompilation = false, textureFormat = Constants.TEXTUREFORMAT_RGBA) { const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation; const localOptions = { uniforms: ThinBlurPostProcess.Uniforms, samplers: ThinBlurPostProcess.Samplers, size: typeof options === "number" ? options : undefined, camera, samplingMode, engine, reusable, textureType, vertexUrl: ThinBlurPostProcess.VertexUrl, indexParameters: { varyingCount: 0, depCount: 0 }, textureFormat, defines, ...options, blockCompilation: true, }; super(name, ThinBlurPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlurPostProcess(name, engine, undefined, undefined, localOptions) : undefined, ...localOptions, }); this._effectWrapper.options.blockCompilation = blockCompilationFinal; this.direction = direction; this.onApplyObservable.add(() => { this._effectWrapper.textureWidth = this._outputTexture ? this._outputTexture.width : this.width; this._effectWrapper.textureHeight = this._outputTexture ? this._outputTexture.height : this.height; }); this.kernel = kernel; } updateEffect(_defines = null, _uniforms = null, _samplers = null, _indexParameters, onCompiled, onError) { this._effectWrapper._updateParameters(onCompiled, onError); } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new BlurPostProcess(parsedPostProcess.name, parsedPostProcess.direction, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, undefined, false); }, parsedPostProcess, scene, rootUrl); } } __decorate([ serializeAsVector2() ], BlurPostProcess.prototype, "direction", null); __decorate([ serialize() ], BlurPostProcess.prototype, "kernel", null); __decorate([ serialize() ], BlurPostProcess.prototype, "packedFloat", null); RegisterClass("BABYLON.BlurPostProcess", BlurPostProcess); /** * Default implementation IShadowGenerator. * This is the main object responsible of generating shadows in the framework. * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows * @see [WebGL](https://playground.babylonjs.com/#IFYDRS#0) * @see [WebGPU](https://playground.babylonjs.com/#IFYDRS#835) */ class ShadowGenerator { /** * Gets the bias: offset applied on the depth preventing acnea (in light direction). */ get bias() { return this._bias; } /** * Sets the bias: offset applied on the depth preventing acnea (in light direction). */ set bias(bias) { this._bias = bias; } /** * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). */ get normalBias() { return this._normalBias; } /** * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). */ set normalBias(normalBias) { this._normalBias = normalBias; } /** * Gets the blur box offset: offset applied during the blur pass. * Only useful if useKernelBlur = false */ get blurBoxOffset() { return this._blurBoxOffset; } /** * Sets the blur box offset: offset applied during the blur pass. * Only useful if useKernelBlur = false */ set blurBoxOffset(value) { if (this._blurBoxOffset === value) { return; } this._blurBoxOffset = value; this._disposeBlurPostProcesses(); } /** * Gets the blur scale: scale of the blurred texture compared to the main shadow map. * 2 means half of the size. */ get blurScale() { return this._blurScale; } /** * Sets the blur scale: scale of the blurred texture compared to the main shadow map. * 2 means half of the size. */ set blurScale(value) { if (this._blurScale === value) { return; } this._blurScale = value; this._disposeBlurPostProcesses(); } /** * Gets the blur kernel: kernel size of the blur pass. * Only useful if useKernelBlur = true */ get blurKernel() { return this._blurKernel; } /** * Sets the blur kernel: kernel size of the blur pass. * Only useful if useKernelBlur = true */ set blurKernel(value) { if (this._blurKernel === value) { return; } this._blurKernel = value; this._disposeBlurPostProcesses(); } /** * Gets whether the blur pass is a kernel blur (if true) or box blur. * Only useful in filtered mode (useBlurExponentialShadowMap...) */ get useKernelBlur() { return this._useKernelBlur; } /** * Sets whether the blur pass is a kernel blur (if true) or box blur. * Only useful in filtered mode (useBlurExponentialShadowMap...) */ set useKernelBlur(value) { if (this._useKernelBlur === value) { return; } this._useKernelBlur = value; this._disposeBlurPostProcesses(); } /** * Gets the depth scale used in ESM mode. */ get depthScale() { return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale(); } /** * Sets the depth scale used in ESM mode. * This can override the scale stored on the light. */ set depthScale(value) { this._depthScale = value; } _validateFilter(filter) { return filter; } /** * Gets the current mode of the shadow generator (normal, PCF, ESM...). * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE */ get filter() { return this._filter; } /** * Sets the current mode of the shadow generator (normal, PCF, ESM...). * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE */ set filter(value) { value = this._validateFilter(value); // Blurring the cubemap is going to be too expensive. Reverting to unblurred version if (this._light.needCube()) { if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { this.useExponentialShadowMap = true; return; } else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { this.useCloseExponentialShadowMap = true; return; } // PCF on cubemap would also be expensive else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { this.usePoissonSampling = true; return; } } // Weblg1 fallback for PCF. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { if (!this._scene.getEngine()._features.supportShadowSamplers) { this.usePoissonSampling = true; return; } } if (this._filter === value) { return; } this._filter = value; this._disposeBlurPostProcesses(); this._applyFilterValues(); this._light._markMeshesAsLightDirty(); } /** * Gets if the current filter is set to Poisson Sampling. */ get usePoissonSampling() { return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING; } /** * Sets the current filter to Poisson Sampling. */ set usePoissonSampling(value) { const filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING); if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) { return; } this.filter = value ? filter : ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to ESM. */ get useExponentialShadowMap() { return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP; } /** * Sets the current filter is to ESM. */ set useExponentialShadowMap(value) { const filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP); if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to filtered ESM. */ get useBlurExponentialShadowMap() { return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP; } /** * Gets if the current filter is set to filtered ESM. */ set useBlurExponentialShadowMap(value) { const filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP); if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ get useCloseExponentialShadowMap() { return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP; } /** * Sets the current filter to "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ set useCloseExponentialShadowMap(value) { const filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP); if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to filtered "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ get useBlurCloseExponentialShadowMap() { return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP; } /** * Sets the current filter to filtered "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ set useBlurCloseExponentialShadowMap(value) { const filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP); if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to "PCF" (percentage closer filtering). */ get usePercentageCloserFiltering() { return this.filter === ShadowGenerator.FILTER_PCF; } /** * Sets the current filter to "PCF" (percentage closer filtering). */ set usePercentageCloserFiltering(value) { const filter = this._validateFilter(ShadowGenerator.FILTER_PCF); if (!value && this.filter !== ShadowGenerator.FILTER_PCF) { return; } this.filter = value ? filter : ShadowGenerator.FILTER_NONE; } /** * Gets the PCF or PCSS Quality. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ get filteringQuality() { return this._filteringQuality; } /** * Sets the PCF or PCSS Quality. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ set filteringQuality(filteringQuality) { if (this._filteringQuality === filteringQuality) { return; } this._filteringQuality = filteringQuality; this._disposeBlurPostProcesses(); this._applyFilterValues(); this._light._markMeshesAsLightDirty(); } /** * Gets if the current filter is set to "PCSS" (contact hardening). */ get useContactHardeningShadow() { return this.filter === ShadowGenerator.FILTER_PCSS; } /** * Sets the current filter to "PCSS" (contact hardening). */ set useContactHardeningShadow(value) { const filter = this._validateFilter(ShadowGenerator.FILTER_PCSS); if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) { return; } this.filter = value ? filter : ShadowGenerator.FILTER_NONE; } /** * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. * Using a ratio helps keeping shape stability independently of the map size. * * It does not account for the light projection as it was having too much * instability during the light setup or during light position changes. * * Only valid if useContactHardeningShadow is true. */ get contactHardeningLightSizeUVRatio() { return this._contactHardeningLightSizeUVRatio; } /** * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. * Using a ratio helps keeping shape stability independently of the map size. * * It does not account for the light projection as it was having too much * instability during the light setup or during light position changes. * * Only valid if useContactHardeningShadow is true. */ set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) { this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio; } /** Gets or sets the actual darkness of a shadow */ get darkness() { return this._darkness; } set darkness(value) { this.setDarkness(value); } /** * Returns the darkness value (float). This can only decrease the actual darkness of a shadow. * 0 means strongest and 1 would means no shadow. * @returns the darkness. */ getDarkness() { return this._darkness; } /** * Sets the darkness value (float). This can only decrease the actual darkness of a shadow. * @param darkness The darkness value 0 means strongest and 1 would means no shadow. * @returns the shadow generator allowing fluent coding. */ setDarkness(darkness) { if (darkness >= 1.0) { this._darkness = 1.0; } else if (darkness <= 0.0) { this._darkness = 0.0; } else { this._darkness = darkness; } return this; } /** Gets or sets the ability to have transparent shadow */ get transparencyShadow() { return this._transparencyShadow; } set transparencyShadow(value) { this.setTransparencyShadow(value); } /** * Sets the ability to have transparent shadow (boolean). * @param transparent True if transparent else False * @returns the shadow generator allowing fluent coding */ setTransparencyShadow(transparent) { this._transparencyShadow = transparent; return this; } /** * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). * @returns The render target texture if present otherwise, null */ getShadowMap() { return this._shadowMap; } /** * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). * @returns The render target texture if the shadow map is present otherwise, null */ getShadowMapForRendering() { if (this._shadowMap2) { return this._shadowMap2; } return this._shadowMap; } /** * Gets the class name of that object * @returns "ShadowGenerator" */ getClassName() { return ShadowGenerator.CLASSNAME; } /** * Helper function to add a mesh and its descendants to the list of shadow casters. * @param mesh Mesh to add * @param includeDescendants boolean indicating if the descendants should be added. Default to true * @returns the Shadow Generator itself */ addShadowCaster(mesh, includeDescendants = true) { if (!this._shadowMap) { return this; } if (!this._shadowMap.renderList) { this._shadowMap.renderList = []; } if (this._shadowMap.renderList.indexOf(mesh) === -1) { this._shadowMap.renderList.push(mesh); } if (includeDescendants) { for (const childMesh of mesh.getChildMeshes()) { if (this._shadowMap.renderList.indexOf(childMesh) === -1) { this._shadowMap.renderList.push(childMesh); } } } return this; } /** * Helper function to remove a mesh and its descendants from the list of shadow casters * @param mesh Mesh to remove * @param includeDescendants boolean indicating if the descendants should be removed. Default to true * @returns the Shadow Generator itself */ removeShadowCaster(mesh, includeDescendants = true) { if (!this._shadowMap || !this._shadowMap.renderList) { return this; } const index = this._shadowMap.renderList.indexOf(mesh); if (index !== -1) { this._shadowMap.renderList.splice(index, 1); } if (includeDescendants) { for (const child of mesh.getChildren()) { this.removeShadowCaster(child); } } return this; } /** * Returns the associated light object. * @returns the light generating the shadow */ getLight() { return this._light; } /** * Gets the shader language used in this generator. */ get shaderLanguage() { return this._shaderLanguage; } _getCamera() { return this._camera ?? this._scene.activeCamera; } /** * Gets or sets the size of the texture what stores the shadows */ get mapSize() { return this._mapSize; } set mapSize(size) { this._mapSize = size; this._light._markMeshesAsLightDirty(); this.recreateShadowMap(); } /** * Creates a ShadowGenerator object. * A ShadowGenerator is the required tool to use the shadows. * Each light casting shadows needs to use its own ShadowGenerator. * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows * @param mapSize The size of the texture what stores the shadows. Example : 1024. * @param light The light object generating the shadows. * @param usefullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: false) * @param forceGLSL defines a boolean indicating if the shader must be compiled in GLSL even if we are using WebGPU */ constructor(mapSize, light, usefullFloatFirst, camera, useRedTextureType, forceGLSL = false) { /** * Observable triggered before the shadow is rendered. Can be used to update internal effect state */ this.onBeforeShadowMapRenderObservable = new Observable(); /** * Observable triggered after the shadow is rendered. Can be used to restore internal effect state */ this.onAfterShadowMapRenderObservable = new Observable(); /** * Observable triggered before a mesh is rendered in the shadow map. * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable) */ this.onBeforeShadowMapRenderMeshObservable = new Observable(); /** * Observable triggered after a mesh is rendered in the shadow map. * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable) */ this.onAfterShadowMapRenderMeshObservable = new Observable(); /** * Specifies if the `ShadowGenerator` should be serialized, `true` to skip serialization. * Note a `ShadowGenerator` will not be serialized if its light has `doNotSerialize=true` */ this.doNotSerialize = false; this._bias = 0.00005; this._normalBias = 0; this._blurBoxOffset = 1; this._blurScale = 2; this._blurKernel = 1; this._useKernelBlur = false; this._filter = ShadowGenerator.FILTER_NONE; this._filteringQuality = ShadowGenerator.QUALITY_HIGH; this._contactHardeningLightSizeUVRatio = 0.1; this._darkness = 0; this._transparencyShadow = false; /** * Enables or disables shadows with varying strength based on the transparency * When it is enabled, the strength of the shadow is taken equal to mesh.visibility * If you enabled an alpha texture on your material, the alpha value red from the texture is also combined to compute the strength: * mesh.visibility * alphaTexture.a * The texture used is the diffuse by default, but it can be set to the opacity by setting useOpacityTextureForTransparentShadow * Note that by definition transparencyShadow must be set to true for enableSoftTransparentShadow to work! */ this.enableSoftTransparentShadow = false; /** * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one */ this.useOpacityTextureForTransparentShadow = false; /** * Controls the extent to which the shadows fade out at the edge of the frustum */ this.frustumEdgeFalloff = 0; /** Shader language used by the generator */ this._shaderLanguage = 0 /* ShaderLanguage.GLSL */; /** * If true the shadow map is generated by rendering the back face of the mesh instead of the front face. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset. * It might on the other hand introduce peter panning. */ this.forceBackFacesOnly = false; this._lightDirection = Vector3.Zero(); this._viewMatrix = Matrix.Zero(); this._projectionMatrix = Matrix.Zero(); this._transformMatrix = Matrix.Zero(); this._cachedPosition = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cachedDirection = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._currentFaceIndex = 0; this._currentFaceIndexCache = 0; this._defaultTextureMatrix = Matrix.Identity(); this._shadersLoaded = false; this._mapSize = mapSize; this._light = light; this._scene = light.getScene(); this._camera = camera ?? null; this._useRedTextureType = !!useRedTextureType; // eslint-disable-next-line @typescript-eslint/no-floating-promises this._initShaderSourceAsync(forceGLSL); let shadowGenerators = light._shadowGenerators; if (!shadowGenerators) { shadowGenerators = light._shadowGenerators = new Map(); } shadowGenerators.set(this._camera, this); this.id = light.id; this._useUBO = this._scene.getEngine().supportsUniformBuffers; if (this._useUBO) { this._sceneUBOs = []; this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`)); } ShadowGenerator._SceneComponentInitialization(this._scene); // Texture type fallback from float to int if not supported. const caps = this._scene.getEngine().getCaps(); if (!usefullFloatFirst) { if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = Constants.TEXTURETYPE_HALF_FLOAT; } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = Constants.TEXTURETYPE_FLOAT; } else { this._textureType = Constants.TEXTURETYPE_UNSIGNED_BYTE; } } else { if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = Constants.TEXTURETYPE_FLOAT; } else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = Constants.TEXTURETYPE_HALF_FLOAT; } else { this._textureType = Constants.TEXTURETYPE_UNSIGNED_BYTE; } } this._initializeGenerator(); this._applyFilterValues(); } _initializeGenerator() { this._light._markMeshesAsLightDirty(); this._initializeShadowMap(); } _createTargetRenderTexture() { const engine = this._scene.getEngine(); if (engine._features.supportDepthStencilTexture) { this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false, undefined, this._useRedTextureType ? Constants.TEXTUREFORMAT_RED : Constants.TEXTUREFORMAT_RGBA); this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? Constants.GREATER : Constants.LESS, true, undefined, undefined, undefined, `DepthStencilForShadowGenerator-${this._light.name}`); } else { this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube()); } this._shadowMap.noPrePassRenderer = true; } _initializeShadowMap() { this._createTargetRenderTexture(); if (this._shadowMap === null) { return; } this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE; this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE; this._shadowMap.anisotropicFilteringLevel = 1; this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); this._shadowMap.renderParticles = false; this._shadowMap.ignoreCameraViewport = true; if (this._storedUniqueId) { this._shadowMap.uniqueId = this._storedUniqueId; } // Custom render function. this._shadowMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => this._renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes); // When preWarm is false, forces the mesh is ready function to true as we are double checking it // in the custom render function. Also it prevents side effects and useless // shader variations in DEPTHPREPASS mode. this._shadowMap.customIsReadyFunction = (mesh, _refreshRate, preWarm) => { if (!preWarm || !mesh.subMeshes) { return true; } let isReady = true; for (const subMesh of mesh.subMeshes) { const renderingMesh = subMesh.getRenderingMesh(); const scene = this._scene; const engine = scene.getEngine(); const material = subMesh.getMaterial(); if (!material || subMesh.verticesCount === 0 || (this.customAllowRendering && !this.customAllowRendering(subMesh))) { continue; } const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); if (batch.mustReturn) { continue; } const hardwareInstancedRendering = engine.getCaps().instancedArrays && ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); const isTransparent = material.needAlphaBlendingForMesh(renderingMesh); isReady = this.isReady(subMesh, hardwareInstancedRendering, isTransparent) && isReady; } return isReady; }; const engine = this._scene.getEngine(); this._shadowMap.onBeforeBindObservable.add(() => { this._currentSceneUBO = this._scene.getSceneUniformBuffer(); engine._debugPushGroup?.(`shadow map generation for pass id ${engine.currentRenderPassId}`, 1); }); // Record Face Index before render. this._shadowMap.onBeforeRenderObservable.add((faceIndex) => { if (this._sceneUBOs) { this._scene.setSceneUniformBuffer(this._sceneUBOs[0]); } this._currentFaceIndex = faceIndex; if (this._filter === ShadowGenerator.FILTER_PCF) { engine.setColorWrite(false); } this.getTransformMatrix(); // generate the view/projection matrix this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix); if (this._useUBO) { this._scene.getSceneUniformBuffer().unbindEffect(); this._scene.finalizeSceneUbo(); } }); // Blur if required after render. this._shadowMap.onAfterUnbindObservable.add(() => { if (this._sceneUBOs) { this._scene.setSceneUniformBuffer(this._currentSceneUBO); } this._scene.updateTransformMatrix(); // restore the view/projection matrices of the active camera if (this._filter === ShadowGenerator.FILTER_PCF) { engine.setColorWrite(true); } if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) { engine._debugPopGroup?.(1); return; } const shadowMap = this.getShadowMapForRendering(); if (shadowMap) { this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true); engine.unBindFramebuffer(shadowMap.renderTarget, true); } engine._debugPopGroup?.(1); }); // Clear according to the chosen filter. const clearZero = new Color4(0, 0, 0, 0); const clearOne = new Color4(1.0, 1.0, 1.0, 1.0); this._shadowMap.onClearObservable.add((engine) => { if (this._filter === ShadowGenerator.FILTER_PCF) { engine.clear(clearOne, false, true, false); } else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { engine.clear(clearZero, true, true, false); } else { engine.clear(clearOne, true, true, false); } }); // Recreate on resize. this._shadowMap.onResizeObservable.add((rtt) => { this._storedUniqueId = this._shadowMap.uniqueId; this._mapSize = rtt.getRenderSize(); this._light._markMeshesAsLightDirty(); this.recreateShadowMap(); }); // Ensures rendering groupids do not erase the depth buffer // or we would lose the shadows information. for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) { this._shadowMap.setRenderingAutoClearDepthStencil(i, false); } } async _initShaderSourceAsync(forceGLSL = false) { const engine = this._scene.getEngine(); if (engine.isWebGPU && !forceGLSL && !ShadowGenerator.ForceGLSL) { this._shaderLanguage = 1 /* ShaderLanguage.WGSL */; await Promise.all([ import('./shadowMap.fragment-i1BGYN9H.esm.js'), import('./shadowMap.vertex-BhmPOFau.esm.js'), import('./depthBoxBlur.fragment-CtfE-83c.esm.js'), import('./shadowMapFragmentSoftTransparentShadow-BNjlowIs.esm.js'), ]); } else { await Promise.all([ import('./shadowMap.fragment-DK7ngjsF.esm.js'), import('./shadowMap.vertex-CGN-5pu0.esm.js'), import('./depthBoxBlur.fragment-DGteVsQp.esm.js'), import('./shadowMapFragmentSoftTransparentShadow-Dv2XyD2X.esm.js'), ]); } this._shadersLoaded = true; } _initializeBlurRTTAndPostProcesses() { const engine = this._scene.getEngine(); const targetSize = this._mapSize / this.blurScale; if (!this.useKernelBlur || this.blurScale !== 1.0) { this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType, undefined, undefined, false); this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE; this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE; this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); } if (this.useKernelBlur) { this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new Vector2(1, 0), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.width = targetSize; this._kernelBlurXPostprocess.height = targetSize; this._kernelBlurXPostprocess.externalTextureSamplerBinding = true; this._kernelBlurXPostprocess.onApplyObservable.add((effect) => { effect.setTexture("textureSampler", this._shadowMap); }); this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new Vector2(0, 1), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.autoClear = false; this._kernelBlurYPostprocess.autoClear = false; if (this._textureType === Constants.TEXTURETYPE_UNSIGNED_BYTE) { this._kernelBlurXPostprocess.packedFloat = true; this._kernelBlurYPostprocess.packedFloat = true; } this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]; } else { this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType, undefined, undefined, undefined, undefined, this._shaderLanguage); this._boxBlurPostprocess.externalTextureSamplerBinding = true; this._boxBlurPostprocess.onApplyObservable.add((effect) => { effect.setFloat2("screenSize", targetSize, targetSize); effect.setTexture("textureSampler", this._shadowMap); }); this._boxBlurPostprocess.autoClear = false; this._blurPostProcesses = [this._boxBlurPostprocess]; } } _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { let index; if (depthOnlySubMeshes.length) { for (index = 0; index < depthOnlySubMeshes.length; index++) { this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]); } } for (index = 0; index < opaqueSubMeshes.length; index++) { this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]); } if (this._tra