diff --git a/docs/en/graphics/material/shader.mdx b/docs/en/graphics/material/shader.mdx index 6a5c56a072..200b79fa66 100644 --- a/docs/en/graphics/material/shader.mdx +++ b/docs/en/graphics/material/shader.mdx @@ -372,14 +372,7 @@ Include code snippets using the `#include` directive: ## Registering Code Snippets -The framework provides many built-in code snippets; developers can register them directly for use: - -```ts showLineNumbers {4} filename="Typescript" -import { registerIncludes } from "@galacean/engine-shader"; - -// Register the built-in ShaderLab code snippets. -registerIncludes(); -``` +Built-in code snippets are automatically registered when the engine is created — no manual registration is needed. For custom snippets, you can register them manually through an interface... diff --git a/docs/zh/graphics/material/shader.mdx b/docs/zh/graphics/material/shader.mdx index 75e5b089d0..2515eab9af 100644 --- a/docs/zh/graphics/material/shader.mdx +++ b/docs/zh/graphics/material/shader.mdx @@ -376,14 +376,7 @@ MRT frag(Varyings input) { ## 注册代码片段 -官方提供了很多内置代码段,开发者可以直接注册后使用: - -```ts showLineNumbers {4} filename="Typescript" -import { registerIncludes } from "@galacean/engine-shader"; - -// 对内置 ShaderLab 代码段注册。 -registerIncludes(); -``` +内置代码段会在引擎创建时自动注册,无需手动调用。 如果是自定义的片段,可以通过接口进行手动注册: ```ts diff --git a/e2e/case/camera-ssao.ts b/e2e/case/camera-ssao.ts index d3dd438f86..03bd2f03df 100644 --- a/e2e/case/camera-ssao.ts +++ b/e2e/case/camera-ssao.ts @@ -22,14 +22,12 @@ import { WebGLEngine, WebGLMode } from "@galacean/engine"; -import { PBRSource, registerIncludes } from "@galacean/engine-shader"; +import { PBRSource } from "@galacean/engine-shader"; import { ShaderLab } from "@galacean/engine-shaderlab"; import { initScreenshot, updateForE2E } from "./.mockForE2E"; Logger.enable(); -registerIncludes(); - // Create engine WebGLEngine.create({ canvas: "canvas", diff --git a/e2e/case/material-pbr-specular.ts b/e2e/case/material-pbr-specular.ts index fe68e36d50..56b5f96189 100644 --- a/e2e/case/material-pbr-specular.ts +++ b/e2e/case/material-pbr-specular.ts @@ -14,14 +14,12 @@ import { Vector3, WebGLEngine } from "@galacean/engine"; -import { PBRSource, registerIncludes } from "@galacean/engine-shader"; +import { PBRSource } from "@galacean/engine-shader"; import { ShaderLab } from "@galacean/engine-shaderlab"; import { initScreenshot, updateForE2E } from "./.mockForE2E"; Logger.enable(); -registerIncludes(); - // Create engine WebGLEngine.create({ canvas: "canvas", shaderLab: new ShaderLab() }).then((engine) => { engine.canvas.resizeByClientSize(); diff --git a/e2e/case/shaderlab-pbr.ts b/e2e/case/shaderlab-pbr.ts index e81ffba62e..b2964ffb2d 100644 --- a/e2e/case/shaderlab-pbr.ts +++ b/e2e/case/shaderlab-pbr.ts @@ -18,14 +18,12 @@ import { Vector3 } from "@galacean/engine"; import { WebGLEngine } from "@galacean/engine-rhi-webgl"; -import { registerIncludes } from "@galacean/engine-shader"; import { initScreenshot, updateForE2E } from "./.mockForE2E"; import { ShaderLab } from "@galacean/engine-shaderlab"; Logger.enable(); const shaderLab = new ShaderLab(); -registerIncludes(); // const pbrShaderSource = `Shader "Water" { diff --git a/examples/src/project-loader.ts b/examples/src/project-loader.ts index e6b1b8000a..b84025b59c 100644 --- a/examples/src/project-loader.ts +++ b/examples/src/project-loader.ts @@ -4,13 +4,9 @@ */ import { AssetType, Logger, WebGLEngine } from "@galacean/engine"; import { ShaderLab } from "@galacean/engine-shaderlab"; -import { registerIncludes } from "@galacean/engine-shader"; Logger.enable(); -const shaderLab = new ShaderLab(); -registerIncludes(); - WebGLEngine.create({ canvas: document.getElementById("canvas") as HTMLCanvasElement, shaderLab diff --git a/examples/src/shaderlab-05-advance.ts b/examples/src/shaderlab-05-advance.ts index 49556680ae..164b64d0a3 100644 --- a/examples/src/shaderlab-05-advance.ts +++ b/examples/src/shaderlab-05-advance.ts @@ -14,7 +14,6 @@ import { Vector3, WebGLEngine } from "@galacean/engine"; -import { registerIncludes } from "@galacean/engine-shader"; import { ShaderLab } from "@galacean/engine-shaderlab"; // 使用引擎内置Shader片段的骨骼动画Unlit着色器 @@ -81,9 +80,6 @@ Shader "Tutorial/05-SkinnedUnlit" { // 主程序 Logger.enable(); -// 注册引擎内置的Shader代码片段 -registerIncludes(); - WebGLEngine.create({ canvas: "canvas", shaderLab: new ShaderLab() }).then(async (engine) => { engine.canvas.resizeByClientSize(); diff --git a/packages/core/package.json b/packages/core/package.json index d2998034f5..fdc71e24d0 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -21,7 +21,8 @@ "types/**/*" ], "dependencies": { - "@galacean/engine-math": "workspace:*" + "@galacean/engine-math": "workspace:*", + "@galacean/engine-shader": "workspace:*" }, "devDependencies": { "@galacean/engine-design": "workspace:*" diff --git a/packages/core/src/Background.ts b/packages/core/src/Background.ts index 8b3f5b01e7..ef90f89f95 100644 --- a/packages/core/src/Background.ts +++ b/packages/core/src/Background.ts @@ -31,8 +31,8 @@ export class Background { /** @internal */ _mesh: ModelMesh; - /** @internal */ - _material: Material; + + private __material: Material; private _solidColor = new Color(0.05087608817155679, 0.05087608817155679, 0.05087608817155679, 1.0); private _texture: Texture2D = null; @@ -93,8 +93,10 @@ export class Background { this.texture = null; this._mesh._addReferCount(-1); this._mesh = null; - this._material._addReferCount(-1); - this._material = null; + if (this.__material) { + this.__material._addReferCount(-1); + this.__material = null; + } this.sky.destroy(); } @@ -102,9 +104,23 @@ export class Background { * Constructor of Background. * @param _engine Engine Which the background belongs to. */ + /** @internal */ + get _material(): Material { + if (!this.__material) { + const material = new Material(this._engine, Shader.find("Sky/BackgroundTexture")); + material.renderState.depthState.compareFunction = CompareFunction.LessEqual; + material._addReferCount(1); + this.__material = material; + } + return this.__material; + } + + set _material(value: Material) { + this.__material = value; + } + constructor(private _engine: Engine) { this._initMesh(_engine); - this._initMaterial(_engine); } /** @@ -162,12 +178,6 @@ export class Background { this._mesh._addReferCount(1); } - private _initMaterial(engine: Engine): void { - const material = (this._material = new Material(engine, Shader.find("background-texture"))); - material.renderState.depthState.compareFunction = CompareFunction.LessEqual; - material._addReferCount(1); - } - private _createPlane(engine: Engine): ModelMesh { const mesh = new ModelMesh(engine); const indices = new Uint8Array([1, 2, 0, 1, 3, 2]); diff --git a/packages/core/src/BasicResources.ts b/packages/core/src/BasicResources.ts index 264cf2ed95..c154c1fa2b 100644 --- a/packages/core/src/BasicResources.ts +++ b/packages/core/src/BasicResources.ts @@ -107,24 +107,50 @@ export class BasicResources { */ readonly blitMesh: ModelMesh; readonly flipYBlitMesh: ModelMesh; - readonly blitMaterial: Material; - readonly blitScreenMaterial: Material; readonly whiteTexture2D: Texture2D; readonly whiteTextureCube: TextureCube; readonly whiteTexture2DArray: Texture2DArray; readonly uintWhiteTexture2D: Texture2D; - readonly spriteDefaultMaterial: Material; - readonly textDefaultMaterial: Material; - readonly spriteMaskDefaultMaterial: Material; - - readonly meshMagentaMaterial: Material; - readonly particleMagentaMaterial: Material; - + private _blitMaterial: Material; + private _blitScreenMaterial: Material; + private _spriteDefaultMaterial: Material; + private _textDefaultMaterial: Material; + private _spriteMaskDefaultMaterial: Material; + private _meshMagentaMaterial: Material; + private _particleMagentaMaterial: Material; private _blinnPhongMaterial: BlinnPhongMaterial; private _prefilteredDFGTexture: Texture2D; + get blitMaterial(): Material { + return (this._blitMaterial ||= this._createBlitMaterial("Utility/Blit")); + } + + get blitScreenMaterial(): Material { + return (this._blitScreenMaterial ||= this._createBlitMaterial("Utility/BlitScreen")); + } + + get spriteDefaultMaterial(): Material { + return (this._spriteDefaultMaterial ||= this._create2DMaterial(this.engine, Shader.find("2D/Sprite"))); + } + + get textDefaultMaterial(): Material { + return (this._textDefaultMaterial ||= this._create2DMaterial(this.engine, Shader.find("2D/Text"))); + } + + get spriteMaskDefaultMaterial(): Material { + return (this._spriteMaskDefaultMaterial ||= this._createSpriteMaskMaterial(this.engine)); + } + + get meshMagentaMaterial(): Material { + return (this._meshMagentaMaterial ||= this._createMagentaMaterial(this.engine, "Unlit")); + } + + get particleMagentaMaterial(): Material { + return (this._particleMagentaMaterial ||= this._createMagentaMaterial(this.engine, "Particle")); + } + get prefilteredDFGTexture(): Texture2D { return this._prefilteredDFGTexture; } @@ -142,19 +168,6 @@ export class BasicResources { -1, -1, 0, 0, // left-bottom -1, 3, 0, 2]); // left-top - const blitMaterial = new Material(engine, Shader.find("blit")); - blitMaterial._addReferCount(1); - blitMaterial.renderState.depthState.enabled = false; - blitMaterial.renderState.depthState.writeEnabled = false; - - const blitScreenMaterial = new Material(engine, Shader.find("blit-screen")); - blitScreenMaterial._addReferCount(1); - blitScreenMaterial.renderState.depthState.enabled = false; - blitScreenMaterial.renderState.depthState.writeEnabled = false; - - this.blitMaterial = blitMaterial; - this.blitScreenMaterial = blitScreenMaterial; - this.blitMesh = this._createBlitMesh(engine, vertices); this.flipYBlitMesh = this._createBlitMesh(engine, flipYVertices); @@ -195,13 +208,6 @@ export class BasicResources { false ); } - - this.spriteDefaultMaterial = this._create2DMaterial(engine, Shader.find("Sprite")); - this.textDefaultMaterial = this._create2DMaterial(engine, Shader.find("Text")); - this.spriteMaskDefaultMaterial = this._createSpriteMaskMaterial(engine); - - this.meshMagentaMaterial = this._createMagentaMaterial(engine, "unlit"); - this.particleMagentaMaterial = this._createMagentaMaterial(engine, "particle-shader"); } /** @@ -326,8 +332,16 @@ export class BasicResources { return material; } + private _createBlitMaterial(shaderName: string): Material { + const material = new Material(this.engine, Shader.find(shaderName)); + material._addReferCount(1); + material.renderState.depthState.enabled = false; + material.renderState.depthState.writeEnabled = false; + return material; + } + private _createSpriteMaskMaterial(engine: Engine): Material { - const material = new Material(engine, Shader.find("SpriteMask")); + const material = new Material(engine, Shader.find("2D/SpriteMask")); material.isGCIgnored = true; return material; } diff --git a/packages/core/src/Engine.ts b/packages/core/src/Engine.ts index 55b0ea0b4c..763af2eb88 100644 --- a/packages/core/src/Engine.ts +++ b/packages/core/src/Engine.ts @@ -633,6 +633,7 @@ export class Engine extends EventDispatcher { if (shaderLab && !Shader._shaderLab) { Shader._shaderLab = shaderLab; + ShaderPool.registerShaders(); } const initializePromises = new Array>(); diff --git a/packages/core/src/lighting/ambientOcclusion/ScalableAmbientObscurancePass.ts b/packages/core/src/lighting/ambientOcclusion/ScalableAmbientObscurancePass.ts index 697e6e2658..bb27849e32 100644 --- a/packages/core/src/lighting/ambientOcclusion/ScalableAmbientObscurancePass.ts +++ b/packages/core/src/lighting/ambientOcclusion/ScalableAmbientObscurancePass.ts @@ -6,19 +6,16 @@ import { Blitter } from "../../RenderPipeline/Blitter"; import { PipelinePass } from "../../RenderPipeline/PipelinePass"; import { PipelineUtils } from "../../RenderPipeline/PipelineUtils"; import { RenderContext } from "../../RenderPipeline/RenderContext"; -import { Shader, ShaderData, ShaderPass, ShaderProperty } from "../../shader"; -import blitVs from "../../shaderlib/extra/Blit.vs.glsl"; +import { Shader, ShaderData, ShaderProperty } from "../../shader"; import { RenderTarget, Texture2D, TextureFilterMode, TextureFormat, TextureWrapMode } from "../../texture"; import { AmbientOcclusionQuality } from "../enums/AmbientOcclusionQuality"; -import bilateralBlurFS from "./shaders/Blur/BilateralBlur.glsl"; -import scalableAmbientOcclusionFS from "./shaders/ScalableAmbientOcclusion.glsl"; /** * @internal * Scalable Ambient Obscurance render pass. */ export class ScalableAmbientObscurancePass extends PipelinePass { - static readonly SHADER_NAME = "ScalableAmbientOcclusion"; + static readonly SHADER_NAME = "AO/ScalableAmbientOcclusion"; private static _invRadiusSquaredProp = ShaderProperty.getByName("material_invRadiusSquared"); private static _intensityProp = ShaderProperty.getByName("material_intensity"); @@ -222,8 +219,3 @@ export class ScalableAmbientObscurancePass extends PipelinePass { this._quality = quality; } } - -Shader.create(ScalableAmbientObscurancePass.SHADER_NAME, [ - new ShaderPass("ScalableAmbientOcclusion", blitVs, scalableAmbientOcclusionFS), - new ShaderPass("BilateralBlur", blitVs, bilateralBlurFS) -]); diff --git a/packages/core/src/material/BlinnPhongMaterial.ts b/packages/core/src/material/BlinnPhongMaterial.ts index e962246cd2..398ca9af7b 100644 --- a/packages/core/src/material/BlinnPhongMaterial.ts +++ b/packages/core/src/material/BlinnPhongMaterial.ts @@ -160,7 +160,7 @@ export class BlinnPhongMaterial extends BaseMaterial { * @param engine - Engine to which the material belongs */ constructor(engine: Engine) { - super(engine, Shader.find("blinn-phong")); + super(engine, Shader.find("BlinnPhong")); const shaderData = this.shaderData; diff --git a/packages/core/src/material/PBRMaterial.ts b/packages/core/src/material/PBRMaterial.ts index ac780d332a..23bc38fc54 100644 --- a/packages/core/src/material/PBRMaterial.ts +++ b/packages/core/src/material/PBRMaterial.ts @@ -757,7 +757,7 @@ export class PBRMaterial extends BaseMaterial { * @param engine - Engine to which the material belongs */ constructor(engine: Engine) { - super(engine, Shader.find("pbr")); + super(engine, Shader.find("PBR")); const shaderData = this.shaderData; diff --git a/packages/core/src/material/UnlitMaterial.ts b/packages/core/src/material/UnlitMaterial.ts index 81fafda761..7eb8f3018c 100644 --- a/packages/core/src/material/UnlitMaterial.ts +++ b/packages/core/src/material/UnlitMaterial.ts @@ -57,7 +57,7 @@ export class UnlitMaterial extends BaseMaterial { * @param engine - Engine to which the material belongs */ constructor(engine: Engine) { - super(engine, Shader.find("unlit")); + super(engine, Shader.find("Unlit")); const shaderData = this.shaderData; diff --git a/packages/core/src/particle/ParticleMaterial.ts b/packages/core/src/particle/ParticleMaterial.ts index 36c95a8547..df13c9f2ce 100644 --- a/packages/core/src/particle/ParticleMaterial.ts +++ b/packages/core/src/particle/ParticleMaterial.ts @@ -11,7 +11,7 @@ export class ParticleMaterial extends EffectMaterial { * @param engine - Engine to which the material belongs */ constructor(engine: Engine) { - super(engine, Shader.find("particle-shader")); + super(engine, Shader.find("Particle")); } /** diff --git a/packages/core/src/postProcess/FinalPass.ts b/packages/core/src/postProcess/FinalPass.ts index 1342f3ab36..62ad0eee80 100644 --- a/packages/core/src/postProcess/FinalPass.ts +++ b/packages/core/src/postProcess/FinalPass.ts @@ -7,12 +7,7 @@ import { PipelinePass } from "../RenderPipeline/PipelinePass"; import { PipelineUtils } from "../RenderPipeline/PipelineUtils"; import { RenderContext } from "../RenderPipeline/RenderContext"; import { Shader } from "../shader"; -import { ShaderLib } from "../shaderlib"; -import BlitVS from "../shaderlib/extra/Blit.vs.glsl"; import { RenderTarget, Texture2D, TextureFilterMode, TextureFormat, TextureWrapMode } from "../texture"; -import FinalAntiAliasingFS from "./shaders/FinalAntiAliasing.fs.glsl"; -import SRGBFS from "./shaders/FinalSRGB.fs.glsl"; -import FXAA3_11 from "./shaders/FXAA/FXAA3_11.glsl"; /** * @internal @@ -28,18 +23,12 @@ export class FinalPass extends PipelinePass { super(engine); // SRGB Material - const sRGBmaterial = new Material(engine, Shader.find("FinalSRGB")); - const sRGBdepthState = sRGBmaterial.renderState.depthState; - sRGBdepthState.enabled = false; - sRGBdepthState.writeEnabled = false; + const sRGBmaterial = new Material(engine, Shader.find("PostProcess/FinalSRGB")); sRGBmaterial._addReferCount(1); this._sRGBmaterial = sRGBmaterial; // FXAA Material - const antiAliasingMaterial = new Material(engine, Shader.find("FinalAntiAliasing")); - const antiAliasingDepthState = antiAliasingMaterial.renderState.depthState; - antiAliasingDepthState.enabled = false; - antiAliasingDepthState.writeEnabled = false; + const antiAliasingMaterial = new Material(engine, Shader.find("PostProcess/FinalAntiAliasing")); antiAliasingMaterial._addReferCount(1); this._antiAliasingMaterial = antiAliasingMaterial; } @@ -92,10 +81,3 @@ export class FinalPass extends PipelinePass { this._inputRenderTarget = null; } } - -Object.assign(ShaderLib, { - FXAA3_11 -}); - -Shader.create("FinalSRGB", BlitVS, SRGBFS); -Shader.create("FinalAntiAliasing", BlitVS, FinalAntiAliasingFS); diff --git a/packages/core/src/postProcess/PostProcessUberPass.ts b/packages/core/src/postProcess/PostProcessUberPass.ts index 41ba066666..d3fd248966 100644 --- a/packages/core/src/postProcess/PostProcessUberPass.ts +++ b/packages/core/src/postProcess/PostProcessUberPass.ts @@ -5,58 +5,43 @@ import { Material } from "../material"; import { Blitter } from "../RenderPipeline/Blitter"; import { PipelineUtils } from "../RenderPipeline/PipelineUtils"; import { Shader } from "../shader"; -import { ShaderLib } from "../shaderlib"; -import blitVs from "../shaderlib/extra/Blit.vs.glsl"; import { RenderTarget, Texture2D, TextureFilterMode, TextureWrapMode } from "../texture"; import { BloomDownScaleMode, BloomEffect, TonemappingEffect } from "./effects"; import { PostProcessManager } from "./PostProcessManager"; import { PostProcessPass, PostProcessPassEvent } from "./PostProcessPass"; -import Filtering from "./shaders/Filtering.glsl"; -import PostCommon from "./shaders/PostCommon.glsl"; -import ACESTonemapping from "./shaders/Tonemapping/ACES/ACESTonemapping.glsl"; -import ColorTransform from "./shaders/Tonemapping/ACES/ColorTransform.glsl"; -import ODT from "./shaders/Tonemapping/ACES/ODT.glsl"; -import RRT from "./shaders/Tonemapping/ACES/RRT.glsl"; -import Tonescale from "./shaders/Tonemapping/ACES/Tonescale.glsl"; -import NeutralTonemapping from "./shaders/Tonemapping/NeutralTonemapping.glsl"; -import UberPost from "./shaders/UberPost.glsl"; export class PostProcessUberPass extends PostProcessPass { - static readonly UBER_SHADER_NAME = "UberPost"; + static readonly UBER_SHADER_NAME = "PostProcess/Uber"; - private _uberMaterial: Material; - - // Bloom - private _bloomMaterial: Material; + private __uberMaterial: Material; + private __bloomMaterial: Material; private _mipDownRT: RenderTarget[] = []; private _mipUpRT: RenderTarget[] = []; + private get _uberMaterial(): Material { + if (!this.__uberMaterial) { + const material = new Material(this.engine, Shader.find(PostProcessUberPass.UBER_SHADER_NAME)); + material.shaderData.setVector4(BloomEffect._bloomIntensityParams, new Vector4()); + material.shaderData.setVector4(BloomEffect._dirtTilingOffsetProp, new Vector4()); + material.shaderData.setColor(BloomEffect._tintProp, new Color()); + this.__uberMaterial = material; + } + return this.__uberMaterial; + } + + private get _bloomMaterial(): Material { + if (!this.__bloomMaterial) { + const material = new Material(this.engine, Shader.find(BloomEffect.SHADER_NAME)); + material.shaderData.setVector4(BloomEffect._bloomParams, new Vector4()); + material.shaderData.setVector4(BloomEffect._lowMipTexelSizeProp, new Vector4()); + this.__bloomMaterial = material; + } + return this.__bloomMaterial; + } + constructor(engine: Engine) { super(engine); this.event = PostProcessPassEvent.AfterUber - 1; - - // Uber Material - const uberMaterial = new Material(engine, Shader.find(PostProcessUberPass.UBER_SHADER_NAME)); - const uberDepthState = uberMaterial.renderState.depthState; - uberDepthState.enabled = false; - uberDepthState.writeEnabled = false; - this._uberMaterial = uberMaterial; - - // Bloom Material - const bloomMaterial = new Material(engine, Shader.find(BloomEffect.SHADER_NAME)); - const bloomDepthState = bloomMaterial.renderState.depthState; - bloomDepthState.enabled = false; - bloomDepthState.writeEnabled = false; - this._bloomMaterial = bloomMaterial; - - // ShaderData initialization - const bloomShaderData = bloomMaterial.shaderData; - const uberShaderData = uberMaterial.shaderData; - bloomShaderData.setVector4(BloomEffect._bloomParams, new Vector4()); - bloomShaderData.setVector4(BloomEffect._lowMipTexelSizeProp, new Vector4()); - uberShaderData.setVector4(BloomEffect._bloomIntensityParams, new Vector4()); - uberShaderData.setVector4(BloomEffect._dirtTilingOffsetProp, new Vector4()); - uberShaderData.setColor(BloomEffect._tintProp, new Color()); } /** @inheritdoc */ @@ -103,8 +88,8 @@ export class PostProcessUberPass extends PostProcessPass { override _onDestroy() { super._onDestroy(); this._releaseBloomRenderTargets(); - this._uberMaterial.destroy(); - this._bloomMaterial.destroy(); + this.__uberMaterial?.destroy(); + this.__bloomMaterial?.destroy(); } private _setupBloom(bloomBlend: BloomEffect, camera: Camera, srcTexture: Texture2D) { @@ -263,16 +248,3 @@ export class PostProcessUberPass extends PostProcessPass { this._mipUpRT.length = 0; } } - -Object.assign(ShaderLib, { - PostCommon, - Filtering, - ODT, - RRT, - Tonescale, - ColorTransform, - NeutralTonemapping, - ACESTonemapping -}); - -Shader.create(PostProcessUberPass.UBER_SHADER_NAME, blitVs, UberPost); diff --git a/packages/core/src/postProcess/effects/BloomEffect.ts b/packages/core/src/postProcess/effects/BloomEffect.ts index 3e07057e4d..8e35f0e7e4 100644 --- a/packages/core/src/postProcess/effects/BloomEffect.ts +++ b/packages/core/src/postProcess/effects/BloomEffect.ts @@ -1,6 +1,5 @@ import { Color } from "@galacean/engine-math"; -import { Shader, ShaderMacro, ShaderPass, ShaderProperty } from "../../shader"; -import blitVs from "../../shaderlib/extra/Blit.vs.glsl"; +import { ShaderMacro, ShaderProperty } from "../../shader"; import { PostProcessEffect } from "../PostProcessEffect"; import { @@ -10,10 +9,6 @@ import { PostProcessEffectFloatParameter, PostProcessEffectTextureParameter } from "../PostProcessEffectParameter"; -import fragBlurH from "../shaders/Bloom/BloomBlurH.glsl"; -import fragBlurV from "../shaders/Bloom/BloomBlurV.glsl"; -import fragPrefilter from "../shaders/Bloom/BloomPrefilter.glsl"; -import fragUpsample from "../shaders/Bloom/BloomUpsample.glsl"; /** * This controls the size of the bloom texture. @@ -26,7 +21,7 @@ export enum BloomDownScaleMode { } export class BloomEffect extends PostProcessEffect { - static readonly SHADER_NAME = "PostProcessEffect Bloom"; + static readonly SHADER_NAME = "PostProcess/Bloom"; // Bloom shader properties /** @internal */ @@ -103,10 +98,3 @@ export class BloomEffect extends PostProcessEffect { return this.enabled && this.intensity.value > 0; } } - -Shader.create(BloomEffect.SHADER_NAME, [ - new ShaderPass("Bloom Prefilter", blitVs, fragPrefilter), - new ShaderPass("Bloom Blur Horizontal", blitVs, fragBlurH), - new ShaderPass("Bloom Blur Vertical", blitVs, fragBlurV), - new ShaderPass("Bloom Upsample", blitVs, fragUpsample) -]); diff --git a/packages/core/src/postProcess/shaders/Bloom/BloomBlurH.glsl b/packages/core/src/postProcess/shaders/Bloom/BloomBlurH.glsl deleted file mode 100644 index 8b51e9bb00..0000000000 --- a/packages/core/src/postProcess/shaders/Bloom/BloomBlurH.glsl +++ /dev/null @@ -1,24 +0,0 @@ -#include - -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; -uniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height - -void main(){ - vec2 texelSize = renderer_texelSize.xy * 2.0; - - // 9-tap gaussian blur on the downsampled source - mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 4.0, 0.0)); - mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 3.0, 0.0)); - mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 2.0, 0.0)); - mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 1.0, 0.0)); - mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v_uv); - mediump vec4 c5 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 1.0, 0.0)); - mediump vec4 c6 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 2.0, 0.0)); - mediump vec4 c7 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 3.0, 0.0)); - mediump vec4 c8 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 4.0, 0.0)); - - gl_FragColor = c0 * 0.01621622 + c1 * 0.05405405 + c2 * 0.12162162 + c3 * 0.19459459 - + c4 * 0.22702703 - + c5 * 0.19459459 + c6 * 0.12162162 + c7 * 0.05405405 + c8 * 0.01621622; -} \ No newline at end of file diff --git a/packages/core/src/postProcess/shaders/Bloom/BloomBlurV.glsl b/packages/core/src/postProcess/shaders/Bloom/BloomBlurV.glsl deleted file mode 100644 index 5c2b4f315d..0000000000 --- a/packages/core/src/postProcess/shaders/Bloom/BloomBlurV.glsl +++ /dev/null @@ -1,20 +0,0 @@ -#include - -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; -uniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height - -void main(){ - vec2 texelSize = renderer_texelSize.xy; - - // Optimized bilinear 5-tap gaussian on the same-sized source (9-tap equivalent) - mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(0.0, texelSize.y * 3.23076923)); - mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(0.0, texelSize.y * 1.38461538)); - mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v_uv); - mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(0.0, texelSize.y * 1.38461538)); - mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(0.0, texelSize.y * 3.23076923)); - - gl_FragColor = c0 * 0.07027027 + c1 * 0.31621622 - + c2 * 0.22702703 - + c3 * 0.31621622 + c4 * 0.07027027; -} \ No newline at end of file diff --git a/packages/core/src/postProcess/shaders/Bloom/BloomPrefilter.glsl b/packages/core/src/postProcess/shaders/Bloom/BloomPrefilter.glsl deleted file mode 100644 index 304046082b..0000000000 --- a/packages/core/src/postProcess/shaders/Bloom/BloomPrefilter.glsl +++ /dev/null @@ -1,56 +0,0 @@ -#include - -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; -uniform vec4 material_BloomParams; // x: threshold (linear), y: threshold knee, z: scatter -uniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height - -void main(){ - #ifdef BLOOM_HQ - vec2 texelSize = renderer_texelSize.xy; - mediump vec4 A = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, -1.0)); - mediump vec4 B = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.0, -1.0)); - mediump vec4 C = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, -1.0)); - mediump vec4 D = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-0.5, -0.5)); - mediump vec4 E = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.5, -0.5)); - mediump vec4 F = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, 0.0)); - mediump vec4 G = texture2DSRGB(renderer_BlitTexture, v_uv); - mediump vec4 H = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, 0.0)); - mediump vec4 I = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-0.5, 0.5)); - mediump vec4 J = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.5, 0.5)); - mediump vec4 K = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, 1.0)); - mediump vec4 L = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.0, 1.0)); - mediump vec4 M = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, 1.0)); - - mediump vec2 scale = vec2(0.5, 0.125); - mediump vec2 div = (1.0 / 4.0) * scale; - - mediump vec4 samplerColor = (D + E + I + J) * div.x; - samplerColor += (A + B + G + F) * div.y; - samplerColor += (B + C + H + G) * div.y; - samplerColor += (F + G + L + K) * div.y; - samplerColor += (G + H + M + L) * div.y; - #else - mediump vec4 samplerColor = texture2DSRGB(renderer_BlitTexture, v_uv); - #endif - - mediump vec3 color = samplerColor.rgb; - - // User controlled clamp to limit crazy high broken spec - color = min(color, HALF_MAX); - - // Thresholding - mediump float brightness = max3(color); - float threshold = material_BloomParams.x; - float thresholdKnee = material_BloomParams.y; - mediump float softness = clamp(brightness - threshold + thresholdKnee, 0.0, 2.0 * thresholdKnee); - softness = (softness * softness) / (4.0 * thresholdKnee + 1e-4); - mediump float multiplier = max(brightness - threshold, softness) / max(brightness, 1e-4); - color *= multiplier; - - // Clamp colors to positive once in prefilter. Encode can have a sqrt, and sqrt(-x) == NaN. Up/Downsample passes would then spread the NaN. - color = max(color, 0.0); - - // Bloom is addtive blend mode, we should set alpha 0 to avoid browser background color dark when canvas alpha and premultiplyAlpha is true - gl_FragColor = vec4(color, 0.0); -} diff --git a/packages/core/src/postProcess/shaders/Bloom/BloomUpsample.glsl b/packages/core/src/postProcess/shaders/Bloom/BloomUpsample.glsl deleted file mode 100644 index 5038ef9dcb..0000000000 --- a/packages/core/src/postProcess/shaders/Bloom/BloomUpsample.glsl +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include - -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; -uniform sampler2D material_lowMipTexture; -uniform vec4 material_BloomParams; // x: threshold (linear), y: threshold knee, z: scatter -uniform vec4 material_lowMipTexelSize; // x: 1/width, y: 1/height, z: width, w: height - -void main(){ - mediump vec4 highMip = texture2DSRGB(renderer_BlitTexture, v_uv); - - #ifdef BLOOM_HQ - mediump vec4 lowMip = sampleTexture2DBicubic(material_lowMipTexture, v_uv, material_lowMipTexelSize); - #else - mediump vec4 lowMip = texture2DSRGB(material_lowMipTexture, v_uv); - #endif - - gl_FragColor = mix(highMip, lowMip, material_BloomParams.z); -} \ No newline at end of file diff --git a/packages/core/src/shader/Shader.ts b/packages/core/src/shader/Shader.ts index f824462eb2..84ac611e0a 100644 --- a/packages/core/src/shader/Shader.ts +++ b/packages/core/src/shader/Shader.ts @@ -46,13 +46,12 @@ export class Shader implements IReferable { * * @param shaderSource - Shader code * @param platformTarget - Shader platform target, @defaultValue ShaderLanguage.GLSLES300 - * @param path - Shader location path * @returns Shader * * @throws * Throw string exception if shaderLab has not been enabled properly. */ - static create(shaderSource: string, platformTarget?: ShaderLanguage, path?: string): Shader; + static create(shaderSource: string, platformTarget?: ShaderLanguage): Shader; /** * Create a shader. @@ -82,7 +81,7 @@ export class Shader implements IReferable { static create( nameOrShaderSource: string, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget?: ShaderLanguage | SubShader[] | ShaderPass[] | string, - fragmentSourceOrPath?: string + fragmentSource?: string ): Shader { let shader: Shader; const shaderMap = Shader._shaderMap; @@ -113,8 +112,7 @@ export class Shader implements IReferable { passSource.contents, passSource.vertexEntry, passSource.fragmentEntry, - vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, - new URL(fragmentSourceOrPath ?? "", ShaderPass._shaderRootPath).href + vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget ); if (!shaderPassSource) { @@ -151,7 +149,7 @@ export class Shader implements IReferable { return; } if (typeof vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget === "string") { - const shaderPass = new ShaderPass(vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, fragmentSourceOrPath); + const shaderPass = new ShaderPass(vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, fragmentSource); shader = new Shader(nameOrShaderSource, [new SubShader("Default", [shaderPass])]); } else { if (vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget.length > 0) { @@ -250,7 +248,12 @@ export class Shader implements IReferable { } private static _resolveUsePass(passName: string): ShaderPass | undefined { - const [shaderName, subShaderName, passNamePart] = passName.split("/"); + // Parse from the end: last segment is pass name, second-to-last is subshader name, + // everything before is the shader name (which may contain "/" like "Utility/ShadowMap"). + const parts = passName.split("/"); + const passNamePart = parts.pop(); + const subShaderName = parts.pop(); + const shaderName = parts.join("/"); return Shader.find(shaderName) ?.subShaders.find((subShader) => subShader.name === subShaderName) ?.passes.find((pass) => pass.name === passNamePart); diff --git a/packages/core/src/shader/ShaderPass.ts b/packages/core/src/shader/ShaderPass.ts index 3473926037..0c01207942 100644 --- a/packages/core/src/shader/ShaderPass.ts +++ b/packages/core/src/shader/ShaderPass.ts @@ -29,8 +29,6 @@ const precisionStr = ` export class ShaderPass extends ShaderPart { /** @internal */ static _shaderPassCounter: number = 0; - /** @internal */ - static _shaderRootPath = "shaders://root/"; /** * @internal diff --git a/packages/core/src/shader/ShaderPool.ts b/packages/core/src/shader/ShaderPool.ts index e677d9e22f..6f7b0094e2 100644 --- a/packages/core/src/shader/ShaderPool.ts +++ b/packages/core/src/shader/ShaderPool.ts @@ -1,40 +1,31 @@ -import { PipelineStage } from "../RenderPipeline/enums/PipelineStage"; -import { BaseMaterial } from "../material/BaseMaterial"; -import blitFs from "../shaderlib/extra/Blit.fs.glsl"; -import blitScreenFs from "../shaderlib/extra/BlitScreen.fs.glsl"; -import blitVs from "../shaderlib/extra/Blit.vs.glsl"; -import skyProceduralFs from "../shaderlib/extra/SkyProcedural.fs.glsl"; -import skyProceduralVs from "../shaderlib/extra/SkyProcedural.vs.glsl"; -import backgroundTextureFs from "../shaderlib/extra/background-texture.fs.glsl"; -import backgroundTextureVs from "../shaderlib/extra/background-texture.vs.glsl"; -import blinnPhongFs from "../shaderlib/extra/blinn-phong.fs.glsl"; -import blinnPhongVs from "../shaderlib/extra/blinn-phong.vs.glsl"; -import depthOnlyFs from "../shaderlib/extra/depthOnly.fs.glsl"; -import depthOnlyVs from "../shaderlib/extra/depthOnly.vs.glsl"; -import particleFs from "../shaderlib/extra/particle.fs.glsl"; -import particleVs from "../shaderlib/extra/particle.vs.glsl"; -import pbrSpecularFs from "../shaderlib/extra/pbr-specular.fs.glsl"; -import pbrFs from "../shaderlib/extra/pbr.fs.glsl"; -import pbrVs from "../shaderlib/extra/pbr.vs.glsl"; -import shadowMapFs from "../shaderlib/extra/shadow-map.fs.glsl"; -import shadowMapVs from "../shaderlib/extra/shadow-map.vs.glsl"; -import skyboxFs from "../shaderlib/extra/skybox.fs.glsl"; -import skyboxVs from "../shaderlib/extra/skybox.vs.glsl"; -import spriteMaskFs from "../shaderlib/extra/sprite-mask.fs.glsl"; -import spriteMaskVs from "../shaderlib/extra/sprite-mask.vs.glsl"; -import spriteFs from "../shaderlib/extra/sprite.fs.glsl"; -import spriteVs from "../shaderlib/extra/sprite.vs.glsl"; -import textFs from "../shaderlib/extra/text.fs.glsl"; -import textVs from "../shaderlib/extra/text.vs.glsl"; -import trailFs from "../shaderlib/extra/trail.fs.glsl"; -import trailVs from "../shaderlib/extra/trail.vs.glsl"; -import unlitFs from "../shaderlib/extra/unlit.fs.glsl"; -import unlitVs from "../shaderlib/extra/unlit.vs.glsl"; +import { + fragmentList, + PBRSource, + PBRSpecularSource, + BlinnPhongSource, + UnlitSource, + SpriteSource, + SpriteMaskSource, + TextSource, + TrailSource, + SkyboxSource, + BackgroundTextureSource, + SkyProceduralSource, + DepthOnlySource, + ShadowMapSource, + BlitSource, + BlitScreenSource, + ParticleSource, + UberShaderSource, + FinalSRGBShaderSource, + FinalAntiAliasingShaderSource, + BloomShaderSource, + SAOShaderSource +} from "@galacean/engine-shader"; +import { Logger } from "../base/Logger"; import { TransformFeedbackShader } from "../graphic/TransformFeedbackShader"; +import { ShaderFactory } from "../shaderlib/ShaderFactory"; import { Shader } from "./Shader"; -import { ShaderPass } from "./ShaderPass"; -import { RenderStateElementKey } from "./enums/RenderStateElementKey"; -import { RenderState } from "./state"; /** * Internal shader pool. @@ -46,49 +37,59 @@ export class ShaderPool { static init(): void { ShaderPool.particleFeedbackShader = new TransformFeedbackShader( - `#include `, + `#include `, `void main() { discard; }`, ["v_FeedbackPosition", "v_FeedbackVelocity"] ); - const shadowCasterPass = new ShaderPass("ShadowCaster", shadowMapVs, shadowMapFs, { - pipelineStage: PipelineStage.ShadowCaster - }); - shadowCasterPass._renderState = new RenderState(); - shadowCasterPass._renderStateDataMap[RenderStateElementKey.RenderQueueType] = - BaseMaterial._shadowCasterRenderQueueProp; - const depthOnlyPass = new ShaderPass("DepthOnly", depthOnlyVs, depthOnlyFs, { - pipelineStage: PipelineStage.DepthOnly - }); - depthOnlyPass._renderState = new RenderState(); - depthOnlyPass._renderStateDataMap[RenderStateElementKey.RenderQueueType] = BaseMaterial._depthOnlyRenderQueueProp; - - const basePasses = [shadowCasterPass, depthOnlyPass]; - - const forwardPassTags = { - pipelineStage: PipelineStage.Forward - }; - - Shader.create("blinn-phong", [ - new ShaderPass("Forward", blinnPhongVs, blinnPhongFs, forwardPassTags), - ...basePasses - ]); - Shader.create("pbr", [new ShaderPass("Forward", pbrVs, pbrFs, forwardPassTags), ...basePasses]); - Shader.create("pbr-specular", [new ShaderPass("Forward", pbrVs, pbrSpecularFs, forwardPassTags), ...basePasses]); - Shader.create("unlit", [new ShaderPass("Forward", unlitVs, unlitFs, forwardPassTags), ...basePasses]); + // Register all include fragments (does not require ShaderLab) + for (const fragment of fragmentList) { + ShaderFactory.registerInclude(fragment.includeKey, fragment.source); + } + } - Shader.create("blit", [new ShaderPass("Forward", blitVs, blitFs, forwardPassTags)]); - Shader.create("blit-screen", [new ShaderPass("Forward", blitVs, blitScreenFs, forwardPassTags)]); - Shader.create("skybox", [new ShaderPass("Forward", skyboxVs, skyboxFs, forwardPassTags)]); - Shader.create("SkyProcedural", [new ShaderPass("Forward", skyProceduralVs, skyProceduralFs, forwardPassTags)]); + /** + * Register all built-in shaders via ShaderLab. + * Must be called after ShaderLab is set on Shader._shaderLab. + */ + static registerShaders(): void { + const sources = [ + // Utility shaders must be created first — material shaders UsePass from them + BlitSource, + BlitScreenSource, + ShadowMapSource, + DepthOnlySource, + // Material shaders + PBRSource, + PBRSpecularSource, + BlinnPhongSource, + UnlitSource, + // Sky shaders + SkyboxSource, + SkyProceduralSource, + BackgroundTextureSource, + // 2D shaders + SpriteSource, + SpriteMaskSource, + TextSource, + TrailSource, + // Particle shader + ParticleSource, + // PostProcess shaders + UberShaderSource, + FinalSRGBShaderSource, + FinalAntiAliasingShaderSource, + BloomShaderSource, + // AO shader + SAOShaderSource + ]; - Shader.create("particle-shader", [new ShaderPass("Forward", particleVs, particleFs, forwardPassTags)]); - Shader.create("trail", [new ShaderPass("Forward", trailVs, trailFs, forwardPassTags)]); - Shader.create("SpriteMask", [new ShaderPass("Forward", spriteMaskVs, spriteMaskFs, forwardPassTags)]); - Shader.create("Sprite", [new ShaderPass("Forward", spriteVs, spriteFs, forwardPassTags)]); - Shader.create("Text", [new ShaderPass("Forward", textVs, textFs, forwardPassTags)]); - Shader.create("background-texture", [ - new ShaderPass("Forward", backgroundTextureVs, backgroundTextureFs, forwardPassTags) - ]); + for (const source of sources) { + try { + Shader.create(source); + } catch (e) { + Logger.warn(`Failed to register built-in shader: ${e.message || e}`); + } + } } } diff --git a/packages/core/src/shaderlib/FogFragment.glsl b/packages/core/src/shaderlib/FogFragment.glsl deleted file mode 100644 index 11718b0c43..0000000000 --- a/packages/core/src/shaderlib/FogFragment.glsl +++ /dev/null @@ -1,4 +0,0 @@ -#if SCENE_FOG_MODE != 0 - float fogIntensity = ComputeFogIntensity(length(v_positionVS)); - gl_FragColor.rgb = mix(scene_FogColor.rgb, gl_FragColor.rgb, fogIntensity); -#endif diff --git a/packages/core/src/shaderlib/FogFragmentDeclaration.glsl b/packages/core/src/shaderlib/FogFragmentDeclaration.glsl deleted file mode 100644 index 6aa7efb2e4..0000000000 --- a/packages/core/src/shaderlib/FogFragmentDeclaration.glsl +++ /dev/null @@ -1,20 +0,0 @@ -#if SCENE_FOG_MODE != 0 - varying vec3 v_positionVS; - - uniform vec4 scene_FogColor; - uniform vec4 scene_FogParams;// (-1/(end-start), end/(end-start), density/ln(2),density/sprt(ln(2))); - - float ComputeFogIntensity(float fogDepth){ - #if SCENE_FOG_MODE == 1 - // (end-z) / (end-start) = z * (-1/(end-start)) + (end/(end-start)) - return clamp(fogDepth * scene_FogParams.x + scene_FogParams.y, 0.0, 1.0); - #elif SCENE_FOG_MODE == 2 - // exp(-z * density) = exp2((-z * density)/ln(2)) = exp2(-z * density/ln(2)) - return clamp(exp2(-fogDepth * scene_FogParams.z), 0.0, 1.0); - #elif SCENE_FOG_MODE == 3 - // exp(-(z * density)^2) = exp2(-(z * density)^2/ln(2)) = exp2(-(z * density/sprt(ln(2)))^2) - float factor = fogDepth * scene_FogParams.w; - return clamp(exp2(-factor * factor), 0.0, 1.0); - #endif - } -#endif diff --git a/packages/core/src/shaderlib/FogVertex.glsl b/packages/core/src/shaderlib/FogVertex.glsl deleted file mode 100644 index c2438c7b83..0000000000 --- a/packages/core/src/shaderlib/FogVertex.glsl +++ /dev/null @@ -1,4 +0,0 @@ -#if SCENE_FOG_MODE != 0 - vec4 positionVS = renderer_MVMat * position; - v_positionVS = positionVS.xyz / positionVS.w; -#endif diff --git a/packages/core/src/shaderlib/FogVertexDeclaration.glsl b/packages/core/src/shaderlib/FogVertexDeclaration.glsl deleted file mode 100644 index 5f131cb91b..0000000000 --- a/packages/core/src/shaderlib/FogVertexDeclaration.glsl +++ /dev/null @@ -1,3 +0,0 @@ -#if SCENE_FOG_MODE != 0 - varying vec3 v_positionVS; -#endif diff --git a/packages/core/src/shaderlib/PositionClipSpaceDeclaration.glsl b/packages/core/src/shaderlib/PositionClipSpaceDeclaration.glsl deleted file mode 100644 index f34a52182c..0000000000 --- a/packages/core/src/shaderlib/PositionClipSpaceDeclaration.glsl +++ /dev/null @@ -1,3 +0,0 @@ -#ifdef SCENE_ENABLE_AMBIENT_OCCLUSION - varying vec4 v_PositionCS; -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/PositionClipSpaceVertex.glsl b/packages/core/src/shaderlib/PositionClipSpaceVertex.glsl deleted file mode 100644 index d0b267aaee..0000000000 --- a/packages/core/src/shaderlib/PositionClipSpaceVertex.glsl +++ /dev/null @@ -1,3 +0,0 @@ -#ifdef SCENE_ENABLE_AMBIENT_OCCLUSION - v_PositionCS = gl_Position; -#endif diff --git a/packages/core/src/shaderlib/ShaderFactory.ts b/packages/core/src/shaderlib/ShaderFactory.ts index e314e4409d..3de78da149 100644 --- a/packages/core/src/shaderlib/ShaderFactory.ts +++ b/packages/core/src/shaderlib/ShaderFactory.ts @@ -92,7 +92,7 @@ export class ShaderFactory { * @param regex The default regex is for engine's builtin glsl `#include` syntax, * since `ShaderLab` use the same parsing function but different syntax for `#include` --- `/^[ \t]*#include +"([\w\d.]+)"/gm` */ - static parseIncludes(src: string, regex = /^[ \t]*#include +<([\w\d.]+)>/gm) { + static parseIncludes(src: string, regex = /^[ \t]*#include +<([\w\d./]+)>/gm) { function replace(match, slice) { var replace = ShaderLib[slice]; diff --git a/packages/core/src/shaderlib/ShaderLib.ts b/packages/core/src/shaderlib/ShaderLib.ts index 7fc81c3696..6cd633f436 100644 --- a/packages/core/src/shaderlib/ShaderLib.ts +++ b/packages/core/src/shaderlib/ShaderLib.ts @@ -1,118 +1,6 @@ -import camera_declare from "./camera_declare.glsl"; -import common from "./common.glsl"; -import common_vert from "./common_vert.glsl"; -import transform_declare from "./transform_declare.glsl"; - -import color_share from "./color_share.glsl"; -import FogFragmentDeclaration from "./FogFragmentDeclaration.glsl"; -import FogVertexDeclaration from "./FogVertexDeclaration.glsl"; -import PositionClipSpaceDeclaration from "./PositionClipSpaceDeclaration.glsl"; -import normal_share from "./normal_share.glsl"; -import uv_share from "./uv_share.glsl"; -import worldpos_share from "./worldpos_share.glsl"; - -import begin_normal_vert from "./begin_normal_vert.glsl"; -import begin_position_vert from "./begin_position_vert.glsl"; - -import blendShape_input from "./blendShape_input.glsl"; -import blendShape_vert from "./blendShape_vert.glsl"; -import color_vert from "./color_vert.glsl"; -import FogVertex from "./FogVertex.glsl"; -import normal_vert from "./normal_vert.glsl"; -import position_vert from "./position_vert.glsl"; -import skinning_vert from "./skinning_vert.glsl"; -import uv_vert from "./uv_vert.glsl"; -import worldpos_vert from "./worldpos_vert.glsl"; - -import FogFragment from "./FogFragment.glsl"; -import PositionClipSpaceVertex from "./PositionClipSpaceVertex.glsl"; -import light_frag_define from "./light_frag_define.glsl"; -import mobile_material_frag from "./mobile_material_frag.glsl"; - -import begin_mobile_frag from "./begin_mobile_frag.glsl"; -import begin_viewdir_frag from "./begin_viewdir_frag.glsl"; - -import mobile_blinnphong_frag from "./mobile_blinnphong_frag.glsl"; - -import noise_cellular from "./noise_cellular.glsl"; -import noise_cellular_2D from "./noise_cellular_2D.glsl"; -import noise_cellular_2x2 from "./noise_cellular_2x2.glsl"; -import noise_cellular_2x2x2 from "./noise_cellular_2x2x2.glsl"; -import noise_cellular_3D from "./noise_cellular_3D.glsl"; -import noise_common from "./noise_common.glsl"; -import noise_perlin from "./noise_perlin.glsl"; -import noise_perlin_2D from "./noise_perlin_2D.glsl"; -import noise_perlin_3D from "./noise_perlin_3D.glsl"; -import noise_perlin_4D from "./noise_perlin_4D.glsl"; -import noise_psrd_2D from "./noise_psrd_2D.glsl"; -import noise_simplex from "./noise_simplex.glsl"; -import noise_simplex_2D from "./noise_simplex_2D.glsl"; -import noise_simplex_3D from "./noise_simplex_3D.glsl"; -import noise_simplex_3D_grad from "./noise_simplex_3D_grad.glsl"; -import noise_simplex_4D from "./noise_simplex_4D.glsl"; - -import PBRShaderLib from "./pbr"; -import ShadowLib from "./shadow"; -import ParticleShaderLib from "./particle"; - -import normal_get from "./normal_get.glsl"; - -export const ShaderLib = { - common, - common_vert, - transform_declare, - camera_declare, - - color_share, - normal_share, - uv_share, - worldpos_share, - FogVertexDeclaration, - FogFragmentDeclaration, - PositionClipSpaceDeclaration, - - begin_normal_vert, - begin_position_vert, - - position_vert, - color_vert, - normal_vert, - skinning_vert, - blendShape_input, - blendShape_vert, - uv_vert, - worldpos_vert, - FogVertex, - - light_frag_define, - mobile_material_frag, - FogFragment, - PositionClipSpaceVertex, - - begin_mobile_frag, - begin_viewdir_frag, - - mobile_blinnphong_frag, - - noise_common, - noise_cellular_2D, - noise_cellular_2x2, - noise_cellular_2x2x2, - noise_cellular_3D, - noise_cellular, - noise_perlin_2D, - noise_perlin_3D, - noise_perlin_4D, - noise_perlin, - noise_psrd_2D, - noise_simplex_2D, - noise_simplex_3D_grad, - noise_simplex_3D, - noise_simplex_4D, - noise_simplex, - - ...ShadowLib, - ...PBRShaderLib, - normal_get, - ...ParticleShaderLib -}; +/** + * @internal + * Shader include library. + * Include fragments are registered at runtime via ShaderFactory.registerInclude(). + */ +export const ShaderLib: Record = {}; diff --git a/packages/core/src/shaderlib/begin_mobile_frag.glsl b/packages/core/src/shaderlib/begin_mobile_frag.glsl deleted file mode 100644 index 270ba1cae4..0000000000 --- a/packages/core/src/shaderlib/begin_mobile_frag.glsl +++ /dev/null @@ -1,24 +0,0 @@ - vec4 ambient = vec4(0.0); - vec4 emission = material_EmissiveColor; - vec4 diffuse = material_BaseColor; - vec4 specular = material_SpecularColor; - - - - #ifdef MATERIAL_HAS_EMISSIVETEXTURE - emission *= texture2DSRGB(material_EmissiveTexture, v_uv); - #endif - - #ifdef MATERIAL_HAS_BASETEXTURE - diffuse *= texture2DSRGB(material_BaseTexture, v_uv); - #endif - - #ifdef RENDERER_ENABLE_VERTEXCOLOR - diffuse *= v_color; - #endif - - #ifdef MATERIAL_HAS_SPECULAR_TEXTURE - specular *= texture2DSRGB(material_SpecularTexture, v_uv); - #endif - - ambient = vec4(scene_EnvMapLight.diffuse * scene_EnvMapLight.diffuseIntensity, 1.0) * diffuse; \ No newline at end of file diff --git a/packages/core/src/shaderlib/begin_normal_vert.glsl b/packages/core/src/shaderlib/begin_normal_vert.glsl deleted file mode 100644 index dbde69137f..0000000000 --- a/packages/core/src/shaderlib/begin_normal_vert.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef MATERIAL_OMIT_NORMAL - #ifdef RENDERER_HAS_NORMAL - vec3 normal = vec3( NORMAL ); - #endif - - #ifdef RENDERER_HAS_TANGENT - vec4 tangent = vec4( TANGENT ); - #endif -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/begin_position_vert.glsl b/packages/core/src/shaderlib/begin_position_vert.glsl deleted file mode 100644 index 811789aafb..0000000000 --- a/packages/core/src/shaderlib/begin_position_vert.glsl +++ /dev/null @@ -1 +0,0 @@ - vec4 position = vec4( POSITION , 1.0 ); diff --git a/packages/core/src/shaderlib/begin_viewdir_frag.glsl b/packages/core/src/shaderlib/begin_viewdir_frag.glsl deleted file mode 100644 index 4a8140ec87..0000000000 --- a/packages/core/src/shaderlib/begin_viewdir_frag.glsl +++ /dev/null @@ -1,7 +0,0 @@ -#ifdef CAMERA_ORTHOGRAPHIC - vec3 V = -camera_Forward; -#else - #ifdef MATERIAL_NEED_WORLD_POS - vec3 V = normalize( camera_Position - v_pos ); - #endif -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/blendShape_input.glsl b/packages/core/src/shaderlib/blendShape_input.glsl deleted file mode 100644 index 1f518e66e6..0000000000 --- a/packages/core/src/shaderlib/blendShape_input.glsl +++ /dev/null @@ -1,55 +0,0 @@ -#ifdef RENDERER_HAS_BLENDSHAPE - #ifdef RENDERER_BLENDSHAPE_USE_TEXTURE - uniform mediump sampler2DArray renderer_BlendShapeTexture; - uniform ivec3 renderer_BlendShapeTextureInfo; - uniform float renderer_BlendShapeWeights[RENDERER_BLENDSHAPE_COUNT]; - #else - attribute vec3 POSITION_BS0; - attribute vec3 POSITION_BS1; - #if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_TANGENT ) - attribute vec3 NORMAL_BS0; - attribute vec3 NORMAL_BS1; - attribute vec3 TANGENT_BS0; - attribute vec3 TANGENT_BS1; - uniform float renderer_BlendShapeWeights[2]; - #else - #if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) || defined( RENDERER_BLENDSHAPE_HAS_TANGENT ) - attribute vec3 POSITION_BS2; - attribute vec3 POSITION_BS3; - #ifdef RENDERER_BLENDSHAPE_HAS_NORMAL - attribute vec3 NORMAL_BS0; - attribute vec3 NORMAL_BS1; - attribute vec3 NORMAL_BS2; - attribute vec3 NORMAL_BS3; - #endif - - #ifdef RENDERER_BLENDSHAPE_HAS_TANGENT - attribute vec3 TANGENT_BS0; - attribute vec3 TANGENT_BS1; - attribute vec3 TANGENT_BS2; - attribute vec3 TANGENT_BS3; - #endif - - uniform float renderer_BlendShapeWeights[4]; - #else - attribute vec3 POSITION_BS2; - attribute vec3 POSITION_BS3; - attribute vec3 POSITION_BS4; - attribute vec3 POSITION_BS5; - attribute vec3 POSITION_BS6; - attribute vec3 POSITION_BS7; - uniform float renderer_BlendShapeWeights[8]; - #endif - #endif - #endif - - #ifdef RENDERER_BLENDSHAPE_USE_TEXTURE - vec3 getBlendShapeVertexElement(int blendShapeIndex, int vertexElementIndex) - { - int y = vertexElementIndex / renderer_BlendShapeTextureInfo.y; - int x = vertexElementIndex - y * renderer_BlendShapeTextureInfo.y; - ivec3 uv = ivec3(x, y , blendShapeIndex); - return texelFetch(renderer_BlendShapeTexture, uv, 0).xyz; - } - #endif -#endif diff --git a/packages/core/src/shaderlib/blendShape_vert.glsl b/packages/core/src/shaderlib/blendShape_vert.glsl deleted file mode 100644 index 2a66a29ca7..0000000000 --- a/packages/core/src/shaderlib/blendShape_vert.glsl +++ /dev/null @@ -1,72 +0,0 @@ -#ifdef RENDERER_HAS_BLENDSHAPE - #ifdef RENDERER_BLENDSHAPE_USE_TEXTURE - int vertexOffset = gl_VertexID * renderer_BlendShapeTextureInfo.x; - for(int i = 0; i < RENDERER_BLENDSHAPE_COUNT; i++){ - int vertexElementOffset = vertexOffset; - float weight = renderer_BlendShapeWeights[i]; - // Warnning: Multiplying by 0 creates weird precision issues, causing rendering anomalies in Ace2 Android13 - if(weight != 0.0){ - position.xyz += getBlendShapeVertexElement(i, vertexElementOffset) * weight; - - #ifndef MATERIAL_OMIT_NORMAL - #if defined( RENDERER_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) - vertexElementOffset += 1; - normal += getBlendShapeVertexElement(i, vertexElementOffset) * weight; - #endif - - #if defined( RENDERER_HAS_TANGENT ) && defined(RENDERER_BLENDSHAPE_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) ) - vertexElementOffset += 1; - tangent.xyz += getBlendShapeVertexElement(i, vertexElementOffset) * weight; - #endif - #endif - } - - } - #else - position.xyz += POSITION_BS0 * renderer_BlendShapeWeights[0]; - position.xyz += POSITION_BS1 * renderer_BlendShapeWeights[1]; - - #if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_TANGENT ) - #ifndef MATERIAL_OMIT_NORMAL - #ifdef RENDERER_HAS_NORMAL - normal += NORMAL_BS0 * renderer_BlendShapeWeights[0]; - normal += NORMAL_BS1 * renderer_BlendShapeWeights[1]; - #endif - #if defined( RENDERER_HAS_TANGENT ) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) ) - tangent.xyz += TANGENT_BS0 * renderer_BlendShapeWeights[0]; - tangent.xyz += TANGENT_BS1 * renderer_BlendShapeWeights[1]; - #endif - #endif - #else - #if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) || defined( RENDERER_BLENDSHAPE_HAS_TANGENT ) - #ifndef MATERIAL_OMIT_NORMAL - position.xyz += POSITION_BS2 * renderer_BlendShapeWeights[2]; - position.xyz += POSITION_BS3 * renderer_BlendShapeWeights[3]; - - #if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_HAS_NORMAL ) - normal += NORMAL_BS0 * renderer_BlendShapeWeights[0]; - normal += NORMAL_BS1 * renderer_BlendShapeWeights[1]; - normal += NORMAL_BS2 * renderer_BlendShapeWeights[2]; - normal += NORMAL_BS3 * renderer_BlendShapeWeights[3]; - #endif - - #if defined(RENDERER_BLENDSHAPE_HAS_TANGENT) && defined( RENDERER_HAS_TANGENT ) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) ) - tangent.xyz += TANGENT_BS0 * renderer_BlendShapeWeights[0]; - tangent.xyz += TANGENT_BS1 * renderer_BlendShapeWeights[1]; - tangent.xyz += TANGENT_BS2 * renderer_BlendShapeWeights[2]; - tangent.xyz += TANGENT_BS3 * renderer_BlendShapeWeights[3]; - #endif - #endif - #else - position.xyz += POSITION_BS2 * renderer_BlendShapeWeights[2]; - position.xyz += POSITION_BS3 * renderer_BlendShapeWeights[3]; - position.xyz += POSITION_BS4 * renderer_BlendShapeWeights[4]; - position.xyz += POSITION_BS5 * renderer_BlendShapeWeights[5]; - position.xyz += POSITION_BS6 * renderer_BlendShapeWeights[6]; - position.xyz += POSITION_BS7 * renderer_BlendShapeWeights[7]; - #endif - #endif - #endif -#endif - - diff --git a/packages/core/src/shaderlib/camera_declare.glsl b/packages/core/src/shaderlib/camera_declare.glsl deleted file mode 100644 index ff42805f78..0000000000 --- a/packages/core/src/shaderlib/camera_declare.glsl +++ /dev/null @@ -1,2 +0,0 @@ -uniform vec3 camera_Position; -uniform vec3 camera_Forward; \ No newline at end of file diff --git a/packages/core/src/shaderlib/color_share.glsl b/packages/core/src/shaderlib/color_share.glsl deleted file mode 100644 index c4f3619d60..0000000000 --- a/packages/core/src/shaderlib/color_share.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef RENDERER_ENABLE_VERTEXCOLOR - -varying vec4 v_color; - -#endif diff --git a/packages/core/src/shaderlib/color_vert.glsl b/packages/core/src/shaderlib/color_vert.glsl deleted file mode 100644 index ecceb61439..0000000000 --- a/packages/core/src/shaderlib/color_vert.glsl +++ /dev/null @@ -1,5 +0,0 @@ - #ifdef RENDERER_ENABLE_VERTEXCOLOR - - v_color = COLOR_0; - - #endif diff --git a/packages/core/src/shaderlib/common.glsl b/packages/core/src/shaderlib/common.glsl deleted file mode 100644 index 82ab3b19ef..0000000000 --- a/packages/core/src/shaderlib/common.glsl +++ /dev/null @@ -1,157 +0,0 @@ -#define PI 3.14159265359 -#define RECIPROCAL_PI 0.31830988618 -#define EPSILON 1e-6 -#define LOG2 1.442695 -#define HALF_MIN 6.103515625e-5 // 2^-14, the same value for 10, 11 and 16-bit: https://www.khronos.org/opengl/wiki/Small_Float_Formats -#define HALF_EPS 4.8828125e-4 // 2^-11, machine epsilon: 1 + EPS = 1 (half of the ULP for 1.0f) - -#define saturate( a ) clamp( a, 0.0, 1.0 ) - -float pow2(float x ) { - return x * x; -} - -vec4 gammaToLinear(vec4 value){ - return vec4( pow(value.rgb, vec3(2.2)), value.a); -} - -vec4 linearToGamma(vec4 value){ - value = max(value, 0.0); - return vec4( pow(value.rgb, vec3(1.0 / 2.2)), value.a); -} - - -// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_framebuffer_sRGB.txt -// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_sRGB_decode.txt -float sRGBToLinear(float value){ - float linearRGBLo = value / 12.92; - float linearRGBHi = pow((value + 0.055) / 1.055, 2.4); - float linearRGB = (value <= 0.04045) ? linearRGBLo : linearRGBHi; - return linearRGB; -} - -vec4 sRGBToLinear(vec4 value){ - return vec4(sRGBToLinear(value.r), sRGBToLinear(value.g), sRGBToLinear(value.b), value.a); -} - -float linearToSRGB(float value){ - value = max(value, 0.0); - return (value <= 0.0031308) ? (value * 12.9232102) : 1.055 * pow(value, 1.0 / 2.4) - 0.055; -} - -vec4 linearToSRGB(vec4 value){ - return vec4(linearToSRGB(value.r), linearToSRGB(value.g), linearToSRGB(value.b), value.a); -} - -// Compatible with devices that do not even support EXT_sRGB in WebGL1.0. -vec4 texture2DSRGB(sampler2D tex, vec2 uv) { - vec4 color = texture2D(tex, uv); - #ifdef ENGINE_NO_SRGB - color = sRGBToLinear(color); - #endif - return color; -} - -vec4 outputSRGBCorrection(vec4 linearIn){ - #ifdef ENGINE_OUTPUT_SRGB_CORRECT - return linearToSRGB(linearIn); - #else - return linearIn; - #endif -} - - -uniform vec4 camera_DepthBufferParams; -uniform vec4 camera_ProjectionParams; - -float remapDepthBufferLinear01(float depth){ - return 1.0 / (camera_DepthBufferParams.x * depth + camera_DepthBufferParams.y); -} - -float remapDepthBufferEyeDepth(float depth){ - #ifdef CAMERA_ORTHOGRAPHIC - return camera_ProjectionParams.y + (camera_ProjectionParams.z - camera_ProjectionParams.y) * depth; - #else - return 1.0 / (camera_DepthBufferParams.z * depth + camera_DepthBufferParams.w); - #endif -} - -// From Next Generation Post Processing in Call of Duty: Advanced Warfare [Jimenez 2014] -// http://advances.realtimerendering.com/s2014/index.html -// sampleCoord must not be normalized (e.g. window coordinates) -float interleavedGradientNoise(vec2 sampleCoord) -{ - const vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189); - return fract(magic.z * fract(dot(sampleCoord, magic.xy))); -} - -#ifdef GRAPHICS_API_WEBGL2 - #define INVERSE_MAT(mat) inverse(mat) -#else - mat2 inverseMat(mat2 m) { - return mat2(m[1][1],-m[0][1], - -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]); - } - mat3 inverseMat(mat3 m) { - float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2]; - float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2]; - float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2]; - - float b01 = a22 * a11 - a12 * a21; - float b11 = -a22 * a10 + a12 * a20; - float b21 = a21 * a10 - a11 * a20; - - float det = a00 * b01 + a01 * b11 + a02 * b21; - - return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11), - b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10), - b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det; - } - mat4 inverseMat(mat4 m) { - float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3], - a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3], - a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3], - a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3], - - b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32, - - det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - return mat4( - a11 * b11 - a12 * b10 + a13 * b09, - a02 * b10 - a01 * b11 - a03 * b09, - a31 * b05 - a32 * b04 + a33 * b03, - a22 * b04 - a21 * b05 - a23 * b03, - a12 * b08 - a10 * b11 - a13 * b07, - a00 * b11 - a02 * b08 + a03 * b07, - a32 * b02 - a30 * b05 - a33 * b01, - a20 * b05 - a22 * b02 + a23 * b01, - a10 * b10 - a11 * b08 + a13 * b06, - a01 * b08 - a00 * b10 - a03 * b06, - a30 * b04 - a31 * b02 + a33 * b00, - a21 * b02 - a20 * b04 - a23 * b00, - a11 * b07 - a10 * b09 - a12 * b06, - a00 * b09 - a01 * b07 + a02 * b06, - a31 * b01 - a30 * b03 - a32 * b00, - a20 * b03 - a21 * b01 + a22 * b00) / det; - } - - #define INVERSE_MAT(mat) inverseMat(mat) -#endif - - -vec3 safeNormalize(vec3 inVec) { - float dp3 = max(float(HALF_MIN), dot(inVec, inVec)); - return inVec * inversesqrt(dp3); -} diff --git a/packages/core/src/shaderlib/common_vert.glsl b/packages/core/src/shaderlib/common_vert.glsl deleted file mode 100644 index 7de75ee182..0000000000 --- a/packages/core/src/shaderlib/common_vert.glsl +++ /dev/null @@ -1,58 +0,0 @@ -attribute vec3 POSITION; - -#ifdef RENDERER_HAS_UV - attribute vec2 TEXCOORD_0; -#endif - -#ifdef RENDERER_HAS_UV1 - attribute vec2 TEXCOORD_1; -#endif - -#ifdef RENDERER_HAS_SKIN - attribute vec4 JOINTS_0; - attribute vec4 WEIGHTS_0; - - #ifdef RENDERER_USE_JOINT_TEXTURE - uniform sampler2D renderer_JointSampler; - uniform float renderer_JointCount; - - mat4 getJointMatrix(sampler2D smp, float index) - { - float base = index / renderer_JointCount; - float hf = 0.5 / renderer_JointCount; - float v = base + hf; - - vec4 m0 = texture2D(smp, vec2(0.125, v )); - vec4 m1 = texture2D(smp, vec2(0.375, v )); - vec4 m2 = texture2D(smp, vec2(0.625, v )); - vec4 m3 = texture2D(smp, vec2(0.875, v )); - - return mat4(m0, m1, m2, m3); - - } - - #else - uniform mat4 renderer_JointMatrix[ RENDERER_JOINTS_NUM ]; - #endif -#endif - -#ifdef RENDERER_ENABLE_VERTEXCOLOR - attribute vec4 COLOR_0; -#endif - - -#include -#include - -uniform vec4 material_TilingOffset; - - -#ifndef MATERIAL_OMIT_NORMAL - #ifdef RENDERER_HAS_NORMAL - attribute vec3 NORMAL; - #endif - - #ifdef RENDERER_HAS_TANGENT - attribute vec4 TANGENT; - #endif -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/Blit.fs.glsl b/packages/core/src/shaderlib/extra/Blit.fs.glsl deleted file mode 100644 index 30eb31fffc..0000000000 --- a/packages/core/src/shaderlib/extra/Blit.fs.glsl +++ /dev/null @@ -1,32 +0,0 @@ -#include - -uniform mediump sampler2D renderer_BlitTexture; -#ifdef HAS_TEX_LOD - uniform float renderer_BlitMipLevel; -#endif - -uniform vec4 renderer_SourceScaleOffset; - -varying vec2 v_uv; - -#ifdef HAS_TEX_LOD - vec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) { - vec4 color = texture2DLodEXT(tex, uv, lod); - #ifdef ENGINE_NO_SRGB - color = sRGBToLinear(color); - #endif - return color; - } -#endif - -void main() { - vec2 uv = v_uv; - uv = uv * renderer_SourceScaleOffset.xy + renderer_SourceScaleOffset.zw; - - #ifdef HAS_TEX_LOD - gl_FragColor = texture2DLodSRGB( renderer_BlitTexture, uv, renderer_BlitMipLevel ); - #else - gl_FragColor = texture2DSRGB( renderer_BlitTexture, uv ); - #endif -} - diff --git a/packages/core/src/shaderlib/extra/Blit.vs.glsl b/packages/core/src/shaderlib/extra/Blit.vs.glsl deleted file mode 100644 index 6952b1214a..0000000000 --- a/packages/core/src/shaderlib/extra/Blit.vs.glsl +++ /dev/null @@ -1,7 +0,0 @@ -attribute vec4 POSITION_UV; -varying vec2 v_uv; - -void main() { - gl_Position = vec4(POSITION_UV.xy, 0.0, 1.0); - v_uv = POSITION_UV.zw; -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/BlitScreen.fs.glsl b/packages/core/src/shaderlib/extra/BlitScreen.fs.glsl deleted file mode 100644 index a15e872bf7..0000000000 --- a/packages/core/src/shaderlib/extra/BlitScreen.fs.glsl +++ /dev/null @@ -1,34 +0,0 @@ -#include - -uniform mediump sampler2D renderer_BlitTexture; -#ifdef HAS_TEX_LOD - uniform float renderer_BlitMipLevel; -#endif - -varying vec2 v_uv; - -#ifdef HAS_TEX_LOD - vec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) { - vec4 color = texture2DLodEXT(tex, uv, lod); - #ifdef ENGINE_NO_SRGB - color = sRGBToLinear(color); - #endif - return color; - } -#endif - -void main() { - vec2 uv = v_uv; - // Screen uv is flipped - uv.y = 1.0 - uv.y; - - #ifdef HAS_TEX_LOD - gl_FragColor = texture2DLodSRGB( renderer_BlitTexture, uv, renderer_BlitMipLevel ); - #else - gl_FragColor = texture2D( renderer_BlitTexture, uv ); - #endif - - // Color space in screen is in gamma space but without sRGB texture, so we need to convert it to linear space manually - gl_FragColor = sRGBToLinear(gl_FragColor); -} - diff --git a/packages/core/src/shaderlib/extra/SkyProcedural.fs.glsl b/packages/core/src/shaderlib/extra/SkyProcedural.fs.glsl deleted file mode 100644 index c63ad838bb..0000000000 --- a/packages/core/src/shaderlib/extra/SkyProcedural.fs.glsl +++ /dev/null @@ -1,79 +0,0 @@ -// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. -// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader) - -#include - -const float MIE_G = -0.990; -const float MIE_G2 = 0.9801; -const float SKY_GROUND_THRESHOLD = 0.02; - -uniform float material_SunSize; -uniform float material_SunSizeConvergence; -uniform vec4 scene_SunlightColor; -uniform vec3 scene_SunlightDirection; - -varying vec3 v_GroundColor; -varying vec3 v_SkyColor; - -#ifdef MATERIAL_SUN_HIGH_QUALITY - varying vec3 v_Vertex; -#elif defined(MATERIAL_SUN_SIMPLE) - varying vec3 v_RayDir; -#else - varying float v_SkyGroundFactor; -#endif - -#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE) - varying vec3 v_SunColor; -#endif - -// Calculates the Mie phase function -float getMiePhase(float eyeCos, float eyeCos2) { - float temp = 1.0 + MIE_G2 - 2.0 * MIE_G * eyeCos; - temp = pow(temp, pow(material_SunSize,0.65) * 10.0); - temp = max(temp,1.0e-4); // prevent division by zero, esp. in half precision - temp = 1.5 * ((1.0 - MIE_G2) / (2.0 + MIE_G2)) * (1.0 + eyeCos2) / temp; - return temp; -} - -// Calculates the sun shape -float calcSunAttenuation(vec3 lightPos, vec3 ray) { - #ifdef MATERIAL_SUN_HIGH_QUALITY - float focusedEyeCos = pow(clamp(dot(lightPos, ray),0.0,1.0), material_SunSizeConvergence); - return getMiePhase(-focusedEyeCos, focusedEyeCos * focusedEyeCos); - #else //MATERIAL_SUN_SIMPLE - vec3 delta = lightPos - ray; - float dist = length(delta); - float spot = 1.0 - smoothstep(0.0, material_SunSize, dist); - return spot * spot; - #endif -} - -void main() { - // if y > 1 [eyeRay.y < -SKY_GROUND_THRESHOLD] - ground - // if y >= 0 and < 1 [eyeRay.y <= 0 and > -SKY_GROUND_THRESHOLD] - horizon - // if y < 0 [eyeRay.y > 0] - sky - vec3 col = vec3(0.0, 0.0, 0.0); - - #ifdef MATERIAL_SUN_HIGH_QUALITY - vec3 ray = normalize(v_Vertex); - float y = ray.y / SKY_GROUND_THRESHOLD; - #elif defined(MATERIAL_SUN_SIMPLE) - vec3 ray = v_RayDir; - float y = ray.y / SKY_GROUND_THRESHOLD; - #else - float y = v_SkyGroundFactor; - #endif - - // if we did precalculate color in vprog: just do lerp between them - col = mix(v_SkyColor, v_GroundColor, clamp(y,0.0,1.0)); - - #if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE) - if (y < 0.0) - col += v_SunColor * calcSunAttenuation(-scene_SunlightDirection, -ray); - #endif - - - gl_FragColor = vec4(col, 1.0); -} - diff --git a/packages/core/src/shaderlib/extra/SkyProcedural.vs.glsl b/packages/core/src/shaderlib/extra/SkyProcedural.vs.glsl deleted file mode 100644 index 4d60b92c7c..0000000000 --- a/packages/core/src/shaderlib/extra/SkyProcedural.vs.glsl +++ /dev/null @@ -1,200 +0,0 @@ -// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. -// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader) - -#define OUTER_RADIUS 1.025 -#define RAYLEIGH (mix(0.0, 0.0025, pow(material_AtmosphereThickness,2.5))) // Rayleigh constant -#define MIE 0.0010 // Mie constant -#define SUN_BRIGHTNESS 20.0 // Sun brightness -#define MAX_SCATTER 50.0 // Maximum scattering value, to prevent math overflows on Adrenos - -const float SKY_GROUND_THRESHOLD = 0.02; -const float outerRadius = OUTER_RADIUS; -const float outerRadius2 = OUTER_RADIUS*OUTER_RADIUS; -const float innerRadius = 1.0; -const float innerRadius2 = 1.0; -const float cameraHeight = 0.0001; - -const float HDSundiskIntensityFactor = 15.0; -const float simpleSundiskIntensityFactor = 27.0; - -const float sunScale = 400.0 * SUN_BRIGHTNESS; -const float kmESun = MIE * SUN_BRIGHTNESS; -const float km4PI = MIE * 4.0 * 3.14159265; -const float scale = 1.0 / (OUTER_RADIUS - 1.0); -const float scaleDepth = 0.25; -const float scaleOverScaleDepth = (1.0 / (OUTER_RADIUS - 1.0)) / 0.25; -const float samples = 2.0; // THIS IS UNROLLED MANUALLY, DON'T TOUCH - -// RGB wavelengths .35 (.62=158), .43 (.68=174), .525 (.75=190) -const vec3 c_DefaultScatteringWavelength = vec3(0.65, 0.57, 0.475); -const vec3 c_VariableRangeForScatteringWavelength = vec3(0.15, 0.15, 0.15); - -attribute vec4 POSITION; - -uniform mat4 camera_VPMat; -uniform vec3 material_SkyTint; -uniform vec3 material_GroundTint; -uniform float material_Exposure; -uniform float material_AtmosphereThickness; -uniform vec4 scene_SunlightColor; -uniform vec3 scene_SunlightDirection; - -varying vec3 v_GroundColor; -varying vec3 v_SkyColor; - -#ifdef MATERIAL_SUN_HIGH_QUALITY - varying vec3 v_Vertex; -#elif defined(MATERIAL_SUN_SIMPLE) - varying vec3 v_RayDir; -#else - varying float v_SkyGroundFactor; -#endif - -#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE) - varying vec3 v_SunColor; -#endif - -#define GAMMA 2.2 -#define COLOR_2_GAMMA(color) pow(color,vec3(1.0/GAMMA)) -#define COLOR_2_LINEAR(color) color - -// Calculates the Rayleigh phase function -float getRayleighPhase(vec3 light, vec3 ray) -{ - float eyeCos = dot(light, ray); - return 0.75 + 0.75 * eyeCos * eyeCos; -} - -float scaleAngle(float inCos) -{ - float x = 1.0 - inCos; - return 0.25 * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25)))); -} - -void main () { - gl_Position = camera_VPMat*vec4(POSITION.xyz,1.0); - - vec3 skyTintInGammaSpace = COLOR_2_GAMMA(material_SkyTint); - vec3 scatteringWavelength = mix(c_DefaultScatteringWavelength-c_VariableRangeForScatteringWavelength,c_DefaultScatteringWavelength+c_VariableRangeForScatteringWavelength,vec3(1.0) - skyTintInGammaSpace); // using Tint in sRGB+ gamma allows for more visually linear interpolation and to keep (0.5) at (128, gray in sRGB) point - vec3 invWavelength = 1.0 / pow(scatteringWavelength, vec3(4.0)); - - float krESun = RAYLEIGH * SUN_BRIGHTNESS; - float kr4PI = RAYLEIGH * 4.0 * 3.14159265; - - vec3 cameraPos = vec3(0.0,innerRadius + cameraHeight,0.0); // The camera's current position - - // Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere) - vec3 eyeRay = normalize(POSITION.xyz); - - float far = 0.0; - vec3 cIn, cOut; - if (eyeRay.y >= 0.0) { - // Sky - // Calculate the length of the "atmosphere" - far = sqrt(outerRadius2 + innerRadius2 * eyeRay.y * eyeRay.y - innerRadius2) - innerRadius * eyeRay.y; - - // Calculate the ray's starting position, then calculate its scattering offset - float height = innerRadius + cameraHeight; - float depth = exp(scaleOverScaleDepth * -cameraHeight); - float startAngle = dot(eyeRay, cameraPos) / height; - float startOffset = depth*scaleAngle(startAngle); - - // Initialize the scattering loop variables - float sampleLength = far / samples; - float scaledLength = sampleLength * scale; - vec3 sampleRay = eyeRay * sampleLength; - vec3 samplePoint = cameraPos + sampleRay * 0.5; - - vec3 frontColor = vec3(0.0); - //unrolling this manually to avoid some platform for loop slow - { - float height = length(samplePoint); - float depth = exp(scaleOverScaleDepth * (innerRadius - height)); - float lightAngle = dot(-scene_SunlightDirection, samplePoint) / height; - float cameraAngle = dot(eyeRay, samplePoint) / height; - float scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle))); - vec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); - - frontColor += attenuate * (depth * scaledLength); - samplePoint += sampleRay; - } - { - float height = length(samplePoint); - float depth = exp(scaleOverScaleDepth * (innerRadius - height)); - float lightAngle = dot(-scene_SunlightDirection, samplePoint) / height; - float cameraAngle = dot(eyeRay, samplePoint) / height; - float scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle))); - vec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); - - frontColor += attenuate * (depth * scaledLength); - samplePoint += sampleRay; - } - - // Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader - cIn = frontColor * (invWavelength * krESun); - cOut = frontColor * kmESun; - } else { - // Ground - far = (-cameraHeight) / (min(-0.001, eyeRay.y)); - vec3 pos = cameraPos + far * eyeRay; - - // Calculate the ray's starting position, then calculate its scattering offset - float depth = exp((-cameraHeight) * (1.0/scaleDepth)); - float cameraAngle = dot(-eyeRay, pos); - float lightAngle = dot(-scene_SunlightDirection, pos); - float cameraScale = scaleAngle(cameraAngle); - float lightScale = scaleAngle(lightAngle); - float cameraOffset = depth*cameraScale; - float temp = lightScale + cameraScale; - - // Initialize the scattering loop variables - float sampleLength = far / samples; - float scaledLength = sampleLength * scale; - vec3 sampleRay = eyeRay * sampleLength; - vec3 samplePoint = cameraPos + sampleRay * 0.5; - - // Now loop through the sample rays - vec3 frontColor = vec3(0.0, 0.0, 0.0); - vec3 attenuate; - - // Loop removed because we kept hitting SM2.0 temp variable limits. Doesn't affect the image too much - { - float height = length(samplePoint); - float depth = exp(scaleOverScaleDepth * (innerRadius - height)); - float scatter = depth*temp - cameraOffset; - attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); - frontColor += attenuate * (depth * scaledLength); - samplePoint += sampleRay; - } - - cIn = frontColor * (invWavelength * krESun + kmESun); - cOut = clamp(attenuate, 0.0, 1.0); - } - - #ifdef MATERIAL_SUN_HIGH_QUALITY - v_Vertex = -POSITION.xyz; - #elif defined(MATERIAL_SUN_SIMPLE) - v_RayDir = -eyeRay; - #else - v_SkyGroundFactor = -eyeRay.y / SKY_GROUND_THRESHOLD; - #endif - - // if we want to calculate color in vprog: - // 1. in case of linear: multiply by _Exposure in here (even in case of lerp it will be common multiplier, so we can skip mul in fshader) - // 2. in case of gamma: do sqrt right away instead of doing that in fshader - - v_GroundColor = material_Exposure * (cIn + COLOR_2_LINEAR(material_GroundTint) * cOut); - v_SkyColor = material_Exposure * (cIn * getRayleighPhase(-scene_SunlightDirection, -eyeRay)); - - - // The sun should have a stable intensity in its course in the sky. Moreover it should match the highlight of a purely specular material. - // This matching was done using the standard shader BRDF1 on the 5/31/2017 - // Finally we want the sun to be always bright even in LDR thus the normalization of the lightColor for low intensity. - float lightColorIntensity = clamp(length(scene_SunlightColor.xyz), 0.25, 1.0); - - #ifdef MATERIAL_SUN_HIGH_QUALITY - v_SunColor = HDSundiskIntensityFactor * clamp(cOut,0.0,1.0) * scene_SunlightColor.xyz / lightColorIntensity; - #elif defined(MATERIAL_SUN_SIMPLE) - v_SunColor = simpleSundiskIntensityFactor * clamp(cOut * sunScale,0.0,1.0) * scene_SunlightColor.xyz / lightColorIntensity; - #endif -} diff --git a/packages/core/src/shaderlib/extra/background-texture.fs.glsl b/packages/core/src/shaderlib/extra/background-texture.fs.glsl deleted file mode 100644 index b639dea805..0000000000 --- a/packages/core/src/shaderlib/extra/background-texture.fs.glsl +++ /dev/null @@ -1,8 +0,0 @@ -#include -uniform sampler2D material_BaseTexture; - -varying vec2 v_uv; - -void main() { - gl_FragColor = texture2DSRGB(material_BaseTexture, v_uv); -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/background-texture.vs.glsl b/packages/core/src/shaderlib/extra/background-texture.vs.glsl deleted file mode 100644 index 4677fc3136..0000000000 --- a/packages/core/src/shaderlib/extra/background-texture.vs.glsl +++ /dev/null @@ -1,11 +0,0 @@ -attribute vec3 POSITION; -attribute vec2 TEXCOORD_0; -varying vec2 v_uv; -uniform vec4 camera_ProjectionParams; - -void main() { - gl_Position = vec4(POSITION, 1.0); - gl_Position.y *= camera_ProjectionParams.x; - - v_uv = TEXCOORD_0; -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/blinn-phong.fs.glsl b/packages/core/src/shaderlib/extra/blinn-phong.fs.glsl deleted file mode 100644 index 0e812d24a1..0000000000 --- a/packages/core/src/shaderlib/extra/blinn-phong.fs.glsl +++ /dev/null @@ -1,31 +0,0 @@ -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -void main() { - - #include - #include - #include - - gl_FragColor = emission + ambient + diffuse + specular; - - #ifdef MATERIAL_IS_TRANSPARENT - gl_FragColor.a = diffuse.a; - #else - gl_FragColor.a = 1.0; - #endif - - #include -} diff --git a/packages/core/src/shaderlib/extra/blinn-phong.vs.glsl b/packages/core/src/shaderlib/extra/blinn-phong.vs.glsl deleted file mode 100644 index aff49181de..0000000000 --- a/packages/core/src/shaderlib/extra/blinn-phong.vs.glsl +++ /dev/null @@ -1,26 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -void main() { - - #include - #include - #include - #include - #include - #include - #include - #include - #include - - #include - #include -} diff --git a/packages/core/src/shaderlib/extra/depthOnly.fs.glsl b/packages/core/src/shaderlib/extra/depthOnly.fs.glsl deleted file mode 100644 index 020aac729d..0000000000 --- a/packages/core/src/shaderlib/extra/depthOnly.fs.glsl +++ /dev/null @@ -1,2 +0,0 @@ -void main() { -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/depthOnly.vs.glsl b/packages/core/src/shaderlib/extra/depthOnly.vs.glsl deleted file mode 100644 index 06ea2dc057..0000000000 --- a/packages/core/src/shaderlib/extra/depthOnly.vs.glsl +++ /dev/null @@ -1,15 +0,0 @@ -#define MATERIAL_OMIT_NORMAL -#include -#include -#include -uniform mat4 camera_VPMat; - - -void main() { - - #include - #include - #include - #include - -} diff --git a/packages/core/src/shaderlib/extra/particle.fs.glsl b/packages/core/src/shaderlib/extra/particle.fs.glsl deleted file mode 100644 index d87f566b2f..0000000000 --- a/packages/core/src/shaderlib/extra/particle.fs.glsl +++ /dev/null @@ -1,37 +0,0 @@ -#include - -varying vec4 v_Color; -varying vec2 v_TextureCoordinate; -uniform sampler2D material_BaseTexture; -uniform vec4 material_BaseColor; - -uniform mediump vec3 material_EmissiveColor; -#ifdef MATERIAL_HAS_EMISSIVETEXTURE - uniform sampler2D material_EmissiveTexture; -#endif - -#ifdef RENDERER_MODE_MESH - varying vec4 v_MeshColor; -#endif - -void main() { - vec4 color = material_BaseColor * v_Color; - - #if defined(RENDERER_MODE_MESH) && defined(RENDERER_ENABLE_VERTEXCOLOR) - color *= v_MeshColor; - #endif - - #ifdef MATERIAL_HAS_BASETEXTURE - color *= texture2DSRGB(material_BaseTexture, v_TextureCoordinate); - #endif - - // Emissive - vec3 emissiveRadiance = material_EmissiveColor; - #ifdef MATERIAL_HAS_EMISSIVETEXTURE - emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_TextureCoordinate).rgb; - #endif - - color.rgb += emissiveRadiance; - - gl_FragColor = color; -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/particle.vs.glsl b/packages/core/src/shaderlib/extra/particle.vs.glsl deleted file mode 100644 index df5af96d8c..0000000000 --- a/packages/core/src/shaderlib/extra/particle.vs.glsl +++ /dev/null @@ -1,190 +0,0 @@ -#if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD) - attribute vec4 a_CornerTextureCoordinate; -#endif - -#ifdef RENDERER_MODE_MESH - attribute vec3 POSITION; - #ifdef RENDERER_ENABLE_VERTEXCOLOR - attribute vec4 COLOR_0; - #endif - attribute vec2 TEXCOORD_0; - varying vec4 v_MeshColor; -#endif - -attribute vec4 a_ShapePositionStartLifeTime; -attribute vec4 a_DirectionTime; -attribute vec4 a_StartColor; -attribute vec3 a_StartSize; -attribute vec3 a_StartRotation0; -attribute float a_StartSpeed; - -//#if defined(COLOR_OVER_LIFETIME) || defined(RENDERER_COL_RANDOM_GRADIENTS) || defined(RENDERER_SOL_RANDOM_CURVES) || defined(RENDERER_SOL_RANDOM_CURVES_SEPARATE) || defined(ROTATION_OVER_LIFE_TIME_RANDOM_CONSTANTS) || defined(ROTATION_OVER_LIFETIME_RANDOM_CURVES) - attribute vec4 a_Random0; -//#endif - -#if defined(RENDERER_TSA_FRAME_RANDOM_CURVES) || defined(RENDERER_VOL_IS_RANDOM_TWO) - attribute vec4 a_Random1; // x:texture sheet animation random -#endif - -#if defined(RENDERER_FOL_CONSTANT_MODE) || defined(RENDERER_FOL_CURVE_MODE) || defined(RENDERER_LVL_MODULE_ENABLED) - attribute vec4 a_Random2; -#endif - -attribute vec3 a_SimulationWorldPosition; -attribute vec4 a_SimulationWorldRotation; - -#ifdef RENDERER_TRANSFORM_FEEDBACK - attribute vec3 a_FeedbackPosition; - attribute vec3 a_FeedbackVelocity; -#endif - -varying vec4 v_Color; -#ifdef MATERIAL_HAS_BASETEXTURE - attribute vec4 a_SimulationUV; - varying vec2 v_TextureCoordinate; -#endif - -uniform float renderer_CurrentTime; -uniform vec3 renderer_Gravity; -uniform vec3 renderer_WorldPosition; -uniform vec4 renderer_WorldRotation; -uniform bool renderer_ThreeDStartRotation; -uniform int renderer_ScalingMode; -uniform vec3 renderer_PositionScale; -uniform vec3 renderer_SizeScale; -uniform vec3 renderer_PivotOffset; - -uniform mat4 camera_ViewMat; -uniform mat4 camera_ProjMat; - -#ifdef RENDERER_MODE_STRETCHED_BILLBOARD - uniform vec3 camera_Position; -#endif -uniform vec3 camera_Forward; // TODO:只有几种广告牌模式需要用 -uniform vec3 camera_Up; - -uniform float renderer_StretchedBillboardLengthScale; -uniform float renderer_StretchedBillboardSpeedScale; -uniform int renderer_SimulationSpace; - -#include -#include -#include -#include -#include -#include -#include - -vec3 computeParticlePosition(in vec3 startVelocity, in float age, in float normalizedAge, vec3 gravityVelocity, vec4 worldRotation, inout vec3 localVelocity, inout vec3 worldVelocity) { - vec3 startPosition = startVelocity * age; - - vec3 finalPosition; - vec3 localPositionOffset = startPosition; - vec3 worldPositionOffset; - - #ifdef _VOL_MODULE_ENABLED - vec3 lifeVelocity; - vec3 velocityPositionOffset = computeVelocityPositionOffset(normalizedAge, age, lifeVelocity); - if (renderer_VOLSpace == 0) { - localVelocity += lifeVelocity; - localPositionOffset += velocityPositionOffset; - } else { - worldVelocity += lifeVelocity; - worldPositionOffset += velocityPositionOffset; - } - #endif - - #ifdef _FOL_MODULE_ENABLED - vec3 forceVelocity; - vec3 forcePositionOffset = computeForcePositionOffset(normalizedAge, age, forceVelocity); - if (renderer_FOLSpace == 0) { - localVelocity += forceVelocity; - localPositionOffset += forcePositionOffset; - } else { - worldVelocity += forceVelocity; - worldPositionOffset += forcePositionOffset; - } - #endif - - finalPosition = rotationByQuaternions(a_ShapePositionStartLifeTime.xyz + localPositionOffset, worldRotation) + worldPositionOffset; - - if (renderer_SimulationSpace == 0) { - finalPosition = finalPosition + renderer_WorldPosition; - } else if (renderer_SimulationSpace == 1) { - finalPosition = finalPosition + a_SimulationWorldPosition; - } - - finalPosition += 0.5 * gravityVelocity * age; - - return finalPosition; -} - -void main() { - float age = renderer_CurrentTime - a_DirectionTime.w; - float normalizedAge = age / a_ShapePositionStartLifeTime.w; - // normalizedAge >= 0.0: skip stale TF slots whose startTime is from a previous playback (e.g. after StopEmittingAndClear). - if (normalizedAge >= 0.0 && normalizedAge < 1.0) { - vec4 worldRotation; - if (renderer_SimulationSpace == 0) { - worldRotation = renderer_WorldRotation; - } else { - worldRotation = a_SimulationWorldRotation; - } - - vec3 localVelocity; - vec3 worldVelocity; - - #ifdef RENDERER_TRANSFORM_FEEDBACK - // Transform Feedback mode: position in simulation space (local or world). - // Local: transform to world; World: use directly. - vec3 center; - if (renderer_SimulationSpace == 0) { - center = rotationByQuaternions(a_FeedbackPosition, worldRotation) + renderer_WorldPosition; - } else if (renderer_SimulationSpace == 1) { - center = a_FeedbackPosition; - } - localVelocity = a_FeedbackVelocity; - worldVelocity = vec3(0.0); - - #ifdef _VOL_MODULE_ENABLED - vec3 instantVOLVelocity; - computeVelocityPositionOffset(normalizedAge, age, instantVOLVelocity); - if (renderer_VOLSpace == 0) { - localVelocity += instantVOLVelocity; - } else { - worldVelocity += instantVOLVelocity; - } - #endif - #else - // Original analytical path - vec3 startVelocity = a_DirectionTime.xyz * a_StartSpeed; - vec3 gravityVelocity = renderer_Gravity * a_Random0.x * age; - localVelocity = startVelocity; - worldVelocity = gravityVelocity; - vec3 center = computeParticlePosition(startVelocity, age, normalizedAge, gravityVelocity, worldRotation, localVelocity, worldVelocity); - #endif - - #include - #include - #include - #include - #include - - gl_Position = camera_ProjMat * camera_ViewMat * vec4(center, 1.0); - v_Color = computeParticleColor(a_StartColor, normalizedAge); - - #ifdef MATERIAL_HAS_BASETEXTURE - vec2 simulateUV; - #if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD) - simulateUV = a_CornerTextureCoordinate.zw * a_SimulationUV.xy + a_SimulationUV.zw; - v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge); - #endif - #ifdef RENDERER_MODE_MESH - simulateUV = a_SimulationUV.zw + TEXCOORD_0 * a_SimulationUV.xy; - v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge); - #endif - #endif - } else { - gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // Discard use out of X(-1,1),Y(-1,1),Z(0,1) - } -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/pbr-specular.fs.glsl b/packages/core/src/shaderlib/extra/pbr-specular.fs.glsl deleted file mode 100644 index 562959cb6b..0000000000 --- a/packages/core/src/shaderlib/extra/pbr-specular.fs.glsl +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include - -#include - -#include -#include -#include -#include - -#include - - -#include -#include - -void main() { - #include - #include -} diff --git a/packages/core/src/shaderlib/extra/pbr.fs.glsl b/packages/core/src/shaderlib/extra/pbr.fs.glsl deleted file mode 100644 index c51e7e47ca..0000000000 --- a/packages/core/src/shaderlib/extra/pbr.fs.glsl +++ /dev/null @@ -1,21 +0,0 @@ -#include -#include -#include - -#include -#include - -#include -#include -#include -#include - -#include - -#include -#include - -void main() { - #include - #include -} diff --git a/packages/core/src/shaderlib/extra/pbr.vs.glsl b/packages/core/src/shaderlib/extra/pbr.vs.glsl deleted file mode 100644 index 4eee89560c..0000000000 --- a/packages/core/src/shaderlib/extra/pbr.vs.glsl +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -void main() { - - #include - #include - #include - #include - #include - #include - #include - #include - #include - - #include - #include - #include -} diff --git a/packages/core/src/shaderlib/extra/shadow-map.fs.glsl b/packages/core/src/shaderlib/extra/shadow-map.fs.glsl deleted file mode 100644 index 53d1f234c0..0000000000 --- a/packages/core/src/shaderlib/extra/shadow-map.fs.glsl +++ /dev/null @@ -1,52 +0,0 @@ -#ifdef ENGINE_NO_DEPTH_TEXTURE - /** - * Decompose and save depth value. - */ - vec4 pack (float depth) { - // Use rgba 4 bytes with a total of 32 bits to store the z value, and the accuracy of 1 byte is 1/256. - const vec4 bitShift = vec4(1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0); - const vec4 bitMask = vec4(1.0/256.0, 1.0/256.0, 1.0/256.0, 0.0); - - vec4 rgbaDepth = fract(depth * bitShift); // Calculate the z value of each point - - // Cut off the value which do not fit in 8 bits - rgbaDepth -= rgbaDepth.gbaa * bitMask; - - return rgbaDepth; - } -#endif - - -uniform vec4 material_BaseColor; -uniform sampler2D material_BaseTexture; -uniform float material_AlphaCutoff; -varying vec2 v_uv; - -void main() { - #if defined(MATERIAL_IS_ALPHA_CUTOFF) || (defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT)) - float alpha = material_BaseColor.a; - #ifdef MATERIAL_HAS_BASETEXTURE - alpha *= texture2D(material_BaseTexture, v_uv).a; - #endif - - #ifdef MATERIAL_IS_ALPHA_CUTOFF - if(alpha < material_AlphaCutoff){ - discard; - } - #endif - - #if defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT) - // Interleaved gradient noise - float noise = fract(52.982919 * fract(dot(vec2(0.06711, 0.00584), gl_FragCoord.xy))); - if (alpha <= noise) { - discard; - }; - #endif - #endif - - #ifdef ENGINE_NO_DEPTH_TEXTURE - gl_FragColor = pack(gl_FragCoord.z); - #else - gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); - #endif -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/extra/shadow-map.vs.glsl b/packages/core/src/shaderlib/extra/shadow-map.vs.glsl deleted file mode 100644 index fae6a4b849..0000000000 --- a/packages/core/src/shaderlib/extra/shadow-map.vs.glsl +++ /dev/null @@ -1,46 +0,0 @@ -#include -#include -#include -#include -#include -uniform mat4 camera_VPMat; -uniform vec2 scene_ShadowBias; // x: depth bias, y: normal bias -uniform vec3 scene_LightDirection; - -vec3 applyShadowBias(vec3 positionWS) { - positionWS -= scene_LightDirection * scene_ShadowBias.x; - return positionWS; -} - -vec3 applyShadowNormalBias(vec3 positionWS, vec3 normalWS) { - float invNdotL = 1.0 - clamp(dot(-scene_LightDirection, normalWS), 0.0, 1.0); - float scale = invNdotL * scene_ShadowBias.y; - positionWS += normalWS * vec3(scale); - return positionWS; -} - -void main() { - - #include - #include - #include - #include - #include - - vec4 positionWS = renderer_ModelMat * position; - - positionWS.xyz = applyShadowBias(positionWS.xyz); - #ifndef MATERIAL_OMIT_NORMAL - #ifdef RENDERER_HAS_NORMAL - vec3 normalWS = normalize( mat3(renderer_NormalMat) * normal ); - positionWS.xyz = applyShadowNormalBias(positionWS.xyz, normalWS); - #endif - #endif - - - vec4 positionCS = camera_VPMat * positionWS; - positionCS.z = max(positionCS.z, -1.0);// clamp to min ndc z - - gl_Position = positionCS; - -} diff --git a/packages/core/src/shaderlib/extra/skybox.fs.glsl b/packages/core/src/shaderlib/extra/skybox.fs.glsl deleted file mode 100644 index 76c755ff39..0000000000 --- a/packages/core/src/shaderlib/extra/skybox.fs.glsl +++ /dev/null @@ -1,18 +0,0 @@ -#include -uniform samplerCube material_CubeTexture; - -varying vec3 v_cubeUV; -uniform float material_Exposure; -uniform vec4 material_TintColor; - -void main() { - vec4 textureColor = textureCube( material_CubeTexture, v_cubeUV ); - - #ifdef ENGINE_NO_SRGB - textureColor = sRGBToLinear(textureColor); - #endif - - textureColor.rgb *= material_Exposure * material_TintColor.rgb; - - gl_FragColor = textureColor; -} diff --git a/packages/core/src/shaderlib/extra/skybox.vs.glsl b/packages/core/src/shaderlib/extra/skybox.vs.glsl deleted file mode 100644 index 16eeb428e0..0000000000 --- a/packages/core/src/shaderlib/extra/skybox.vs.glsl +++ /dev/null @@ -1,20 +0,0 @@ -#include - -uniform mat4 camera_VPMat; - -varying vec3 v_cubeUV; -uniform float material_Rotation; - -vec4 rotateY(vec4 v, float angle) { - const float deg2rad = 3.1415926 / 180.0; - float radian = angle * deg2rad; - float sina = sin(radian); - float cosa = cos(radian); - mat2 m = mat2(cosa, -sina, sina, cosa); - return vec4(m * v.xz, v.yw).xzyw; -} - -void main() { - v_cubeUV = POSITION; - gl_Position = camera_VPMat * rotateY(vec4(POSITION, 1.0), material_Rotation); -} diff --git a/packages/core/src/shaderlib/extra/sprite-mask.fs.glsl b/packages/core/src/shaderlib/extra/sprite-mask.fs.glsl deleted file mode 100644 index d08acfcbae..0000000000 --- a/packages/core/src/shaderlib/extra/sprite-mask.fs.glsl +++ /dev/null @@ -1,13 +0,0 @@ -uniform sampler2D renderer_MaskTexture; -uniform float renderer_MaskAlphaCutoff; -varying vec2 v_uv; - -void main() -{ - vec4 color = texture2D(renderer_MaskTexture, v_uv); - if (color.a < renderer_MaskAlphaCutoff) { - discard; - } - - gl_FragColor = color; -} diff --git a/packages/core/src/shaderlib/extra/sprite-mask.vs.glsl b/packages/core/src/shaderlib/extra/sprite-mask.vs.glsl deleted file mode 100644 index cdbc97767e..0000000000 --- a/packages/core/src/shaderlib/extra/sprite-mask.vs.glsl +++ /dev/null @@ -1,12 +0,0 @@ -uniform mat4 camera_VPMat; - -attribute vec3 POSITION; -attribute vec2 TEXCOORD_0; - -varying vec2 v_uv; - -void main() -{ - gl_Position = camera_VPMat * vec4(POSITION, 1.0); - v_uv = TEXCOORD_0; -} diff --git a/packages/core/src/shaderlib/extra/sprite.fs.glsl b/packages/core/src/shaderlib/extra/sprite.fs.glsl deleted file mode 100644 index 7a5448dc9e..0000000000 --- a/packages/core/src/shaderlib/extra/sprite.fs.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#include -uniform sampler2D renderer_SpriteTexture; - -varying vec2 v_uv; -varying vec4 v_color; - -void main() -{ - vec4 baseColor = texture2DSRGB(renderer_SpriteTexture, v_uv); - gl_FragColor = baseColor * v_color; -} diff --git a/packages/core/src/shaderlib/extra/sprite.vs.glsl b/packages/core/src/shaderlib/extra/sprite.vs.glsl deleted file mode 100644 index 37a6b2d333..0000000000 --- a/packages/core/src/shaderlib/extra/sprite.vs.glsl +++ /dev/null @@ -1,16 +0,0 @@ -uniform mat4 renderer_MVPMat; - -attribute vec3 POSITION; -attribute vec2 TEXCOORD_0; -attribute vec4 COLOR_0; - -varying vec2 v_uv; -varying vec4 v_color; - -void main() -{ - gl_Position = renderer_MVPMat * vec4(POSITION, 1.0); - - v_uv = TEXCOORD_0; - v_color = COLOR_0; -} diff --git a/packages/core/src/shaderlib/extra/text.fs.glsl b/packages/core/src/shaderlib/extra/text.fs.glsl deleted file mode 100644 index 8fe1125d69..0000000000 --- a/packages/core/src/shaderlib/extra/text.fs.glsl +++ /dev/null @@ -1,15 +0,0 @@ -uniform sampler2D renderElement_TextTexture; - -varying vec2 v_uv; -varying vec4 v_color; - -void main() -{ - vec4 texColor = texture2D(renderElement_TextTexture, v_uv); - #ifdef GRAPHICS_API_WEBGL2 - float coverage = texColor.r; - #else - float coverage = texColor.a; - #endif - gl_FragColor = vec4(v_color.rgb, v_color.a * coverage); -} diff --git a/packages/core/src/shaderlib/extra/text.vs.glsl b/packages/core/src/shaderlib/extra/text.vs.glsl deleted file mode 100644 index 37a6b2d333..0000000000 --- a/packages/core/src/shaderlib/extra/text.vs.glsl +++ /dev/null @@ -1,16 +0,0 @@ -uniform mat4 renderer_MVPMat; - -attribute vec3 POSITION; -attribute vec2 TEXCOORD_0; -attribute vec4 COLOR_0; - -varying vec2 v_uv; -varying vec4 v_color; - -void main() -{ - gl_Position = renderer_MVPMat * vec4(POSITION, 1.0); - - v_uv = TEXCOORD_0; - v_color = COLOR_0; -} diff --git a/packages/core/src/shaderlib/extra/trail.fs.glsl b/packages/core/src/shaderlib/extra/trail.fs.glsl deleted file mode 100644 index 4c009b9153..0000000000 --- a/packages/core/src/shaderlib/extra/trail.fs.glsl +++ /dev/null @@ -1,34 +0,0 @@ -#include - -varying vec2 v_uv; -varying vec4 v_color; - -uniform vec4 material_BaseColor; - -#ifdef MATERIAL_HAS_BASETEXTURE - uniform sampler2D material_BaseTexture; -#endif - -uniform mediump vec3 material_EmissiveColor; -#ifdef MATERIAL_HAS_EMISSIVETEXTURE - uniform sampler2D material_EmissiveTexture; -#endif - -void main() { - vec4 color = material_BaseColor * v_color; - - #ifdef MATERIAL_HAS_BASETEXTURE - color *= texture2DSRGB(material_BaseTexture, v_uv); - #endif - - // Emissive - vec3 emissiveRadiance = material_EmissiveColor; - #ifdef MATERIAL_HAS_EMISSIVETEXTURE - emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_uv).rgb; - #endif - - color.rgb += emissiveRadiance; - - gl_FragColor = color; -} - diff --git a/packages/core/src/shaderlib/extra/trail.vs.glsl b/packages/core/src/shaderlib/extra/trail.vs.glsl deleted file mode 100644 index 960ce0978b..0000000000 --- a/packages/core/src/shaderlib/extra/trail.vs.glsl +++ /dev/null @@ -1,55 +0,0 @@ -attribute vec4 a_PositionBirthTime; // xyz: World position, w: Birth time (used by CPU only) -attribute vec4 a_CornerTangent; // x: Corner (-1 or 1), yzw: Tangent direction -attribute float a_Distance; // Absolute cumulative distance (written once per point) - -uniform vec4 renderer_TrailParams; // x: TextureMode (0: Stretch, 1: Tile), y: TextureScaleX, z: TextureScaleY -uniform vec2 renderer_DistanceParams; // x: HeadDistance, y: TailDistance -uniform vec3 camera_Position; -uniform mat4 camera_ViewMat; -uniform mat4 camera_ProjMat; -uniform vec2 renderer_WidthCurve[4]; // Width curve (4 keyframes max: x=time, y=value) -uniform vec4 renderer_ColorKeys[4]; // Color gradient (x=time, yzw=rgb) -uniform vec2 renderer_AlphaKeys[4]; // Alpha gradient (x=time, y=alpha) -uniform vec4 renderer_CurveMaxTime; // x: colorMaxTime, y: alphaMaxTime, z: widthMaxTime - -varying vec2 v_uv; -varying vec4 v_color; - -#include - -void main() { - vec3 position = a_PositionBirthTime.xyz; - float corner = a_CornerTangent.x; - vec3 tangent = a_CornerTangent.yzw; - - // Distance-based relative position: 0=head(newest), 1=tail(oldest) - float distFromHead = renderer_DistanceParams.x - a_Distance; - float totalDist = renderer_DistanceParams.x - renderer_DistanceParams.y; - float relativePos = totalDist > 0.0 ? distFromHead / totalDist : 0.0; - - // Billboard: expand perpendicular to tangent and view direction - vec3 toCamera = normalize(camera_Position - position); - vec3 right = cross(tangent, toCamera); - float rightLenSq = dot(right, right); - if (rightLenSq < 0.000001) { - right = cross(tangent, vec3(0.0, 1.0, 0.0)); - rightLenSq = dot(right, right); - if (rightLenSq < 0.000001) { - right = cross(tangent, vec3(1.0, 0.0, 0.0)); - rightLenSq = dot(right, right); - } - } - right = right * inversesqrt(rightLenSq); - - float width = evaluateParticleCurve(renderer_WidthCurve, min(relativePos, renderer_CurveMaxTime.z)); - vec3 worldPosition = position + right * width * 0.5 * corner; - - gl_Position = camera_ProjMat * camera_ViewMat * vec4(worldPosition, 1.0); - - // u = position along trail (affected by textureMode), v = corner side. - float u = renderer_TrailParams.x == 0.0 ? relativePos : distFromHead; - float v = corner * 0.5 + 0.5; - v_uv = vec2(u * renderer_TrailParams.y, v * renderer_TrailParams.z); - - v_color = evaluateParticleGradient(renderer_ColorKeys, renderer_CurveMaxTime.x, renderer_AlphaKeys, renderer_CurveMaxTime.y, relativePos); -} diff --git a/packages/core/src/shaderlib/extra/unlit.fs.glsl b/packages/core/src/shaderlib/extra/unlit.fs.glsl deleted file mode 100644 index b39841a7d8..0000000000 --- a/packages/core/src/shaderlib/extra/unlit.fs.glsl +++ /dev/null @@ -1,32 +0,0 @@ -#include -#include -#include - -uniform vec4 material_BaseColor; -uniform float material_AlphaCutoff; - -#ifdef MATERIAL_HAS_BASETEXTURE - uniform sampler2D material_BaseTexture; -#endif - -void main() { - vec4 baseColor = material_BaseColor; - - #ifdef MATERIAL_HAS_BASETEXTURE - baseColor *= texture2DSRGB(material_BaseTexture, v_uv); - #endif - - #ifdef MATERIAL_IS_ALPHA_CUTOFF - if( baseColor.a < material_AlphaCutoff ) { - discard; - } - #endif - - gl_FragColor = baseColor; - - #ifndef MATERIAL_IS_TRANSPARENT - gl_FragColor.a = 1.0; - #endif - - #include -} diff --git a/packages/core/src/shaderlib/extra/unlit.vs.glsl b/packages/core/src/shaderlib/extra/unlit.vs.glsl deleted file mode 100644 index d597274f11..0000000000 --- a/packages/core/src/shaderlib/extra/unlit.vs.glsl +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include -#include -#include -#include - -void main() { - - #include - #include - #include - #include - #include - - #include -} diff --git a/packages/core/src/shaderlib/light_frag_define.glsl b/packages/core/src/shaderlib/light_frag_define.glsl deleted file mode 100644 index 316bbba991..0000000000 --- a/packages/core/src/shaderlib/light_frag_define.glsl +++ /dev/null @@ -1,94 +0,0 @@ -// Directional light -#ifdef SCENE_DIRECT_LIGHT_COUNT - - struct DirectLight { - vec3 color; - vec3 direction; - }; - - uniform ivec2 scene_DirectLightCullingMask[SCENE_DIRECT_LIGHT_COUNT]; - uniform vec3 scene_DirectLightColor[SCENE_DIRECT_LIGHT_COUNT]; - uniform vec3 scene_DirectLightDirection[SCENE_DIRECT_LIGHT_COUNT]; - -#endif - - -// Point light -#ifdef SCENE_POINT_LIGHT_COUNT - - struct PointLight { - vec3 color; - vec3 position; - float distance; - }; - - uniform ivec2 scene_PointLightCullingMask[ SCENE_POINT_LIGHT_COUNT ]; - uniform vec3 scene_PointLightColor[ SCENE_POINT_LIGHT_COUNT ]; - uniform vec3 scene_PointLightPosition[ SCENE_POINT_LIGHT_COUNT ]; - uniform float scene_PointLightDistance[ SCENE_POINT_LIGHT_COUNT ]; - -#endif - - -// Spot light -#ifdef SCENE_SPOT_LIGHT_COUNT - - struct SpotLight { - vec3 color; - vec3 position; - vec3 direction; - float distance; - float angleCos; - float penumbraCos; - }; - - uniform ivec2 scene_SpotLightCullingMask[ SCENE_SPOT_LIGHT_COUNT ]; - uniform vec3 scene_SpotLightColor[ SCENE_SPOT_LIGHT_COUNT ]; - uniform vec3 scene_SpotLightPosition[ SCENE_SPOT_LIGHT_COUNT ]; - uniform vec3 scene_SpotLightDirection[ SCENE_SPOT_LIGHT_COUNT ]; - uniform float scene_SpotLightDistance[ SCENE_SPOT_LIGHT_COUNT ]; - uniform float scene_SpotLightAngleCos[ SCENE_SPOT_LIGHT_COUNT ]; - uniform float scene_SpotLightPenumbraCos[ SCENE_SPOT_LIGHT_COUNT ]; - -#endif - -// Ambient light -struct EnvMapLight { - vec3 diffuse; - float mipMapLevel; - float diffuseIntensity; - float specularIntensity; -}; - - -uniform EnvMapLight scene_EnvMapLight; -uniform ivec4 renderer_Layer; - -#ifdef SCENE_USE_SH - uniform vec3 scene_EnvSH[9]; -#endif - -#ifdef SCENE_USE_SPECULAR_ENV - uniform samplerCube scene_EnvSpecularSampler; -#endif - -#ifndef GRAPHICS_API_WEBGL2 -bool isBitSet(float value, float mask, float bitIndex) -{ - return mod(floor(value / pow(2.0, bitIndex)), 2.0) == 1.0 && mod(floor(mask / pow(2.0, bitIndex)), 2.0) == 1.0; -} -#endif - -bool isRendererCulledByLight(ivec2 rendererLayer, ivec2 lightCullingMask) -{ - #ifdef GRAPHICS_API_WEBGL2 - return !((rendererLayer.x & lightCullingMask.x) != 0 || (rendererLayer.y & lightCullingMask.y) != 0); - #else - for (int i = 0; i < 16; i++) { - if (isBitSet( float(rendererLayer.x), float(lightCullingMask.x), float(i)) || isBitSet( float(rendererLayer.y), float(lightCullingMask.y), float(i))) { - return false; - } - } - return true; - #endif -} diff --git a/packages/core/src/shaderlib/mobile_blinnphong_frag.glsl b/packages/core/src/shaderlib/mobile_blinnphong_frag.glsl deleted file mode 100644 index 41876b7022..0000000000 --- a/packages/core/src/shaderlib/mobile_blinnphong_frag.glsl +++ /dev/null @@ -1,100 +0,0 @@ - #ifdef MATERIAL_HAS_NORMALTEXTURE - mat3 tbn = getTBN(gl_FrontFacing); - vec3 N = getNormalByNormalTexture(tbn, material_NormalTexture, material_NormalIntensity, v_uv, gl_FrontFacing); - #else - vec3 N = getNormal(gl_FrontFacing); - #endif - - vec3 lightDiffuse = vec3( 0.0, 0.0, 0.0 ); - vec3 lightSpecular = vec3( 0.0, 0.0, 0.0 ); - float shadowAttenuation = 1.0; - - #ifdef SCENE_DIRECT_LIGHT_COUNT - shadowAttenuation = 1.0; - #ifdef SCENE_IS_CALCULATE_SHADOWS - shadowAttenuation *= sampleShadowMap(); - #endif - - DirectLight directionalLight; - for( int i = 0; i < SCENE_DIRECT_LIGHT_COUNT; i++ ) { - if(!isRendererCulledByLight(renderer_Layer.xy, scene_DirectLightCullingMask[i])){ - directionalLight.color = scene_DirectLightColor[i]; - #ifdef SCENE_IS_CALCULATE_SHADOWS - if (i == 0) { // Sun light index is always 0 - directionalLight.color *= shadowAttenuation; - } - #endif - directionalLight.direction = scene_DirectLightDirection[i]; - - float d = max(dot(N, -directionalLight.direction), 0.0); - lightDiffuse += directionalLight.color * d; - - vec3 halfDir = normalize( V - directionalLight.direction ); - float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess ); - lightSpecular += directionalLight.color * s; - } - } - - #endif - - #ifdef SCENE_POINT_LIGHT_COUNT - PointLight pointLight; - for( int i = 0; i < SCENE_POINT_LIGHT_COUNT; i++ ) { - if(!isRendererCulledByLight(renderer_Layer.xy, scene_PointLightCullingMask[i])){ - pointLight.color = scene_PointLightColor[i]; - pointLight.position = scene_PointLightPosition[i]; - pointLight.distance = scene_PointLightDistance[i]; - - vec3 direction = v_pos - pointLight.position; - float dist = length( direction ); - direction /= dist; - float decay = clamp(1.0 - pow(dist / pointLight.distance, 4.0), 0.0, 1.0); - - float d = max( dot( N, -direction ), 0.0 ) * decay; - lightDiffuse += pointLight.color * d; - - vec3 halfDir = normalize( V - direction ); - float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess ) * decay; - lightSpecular += pointLight.color * s; - } - } - - #endif - - #ifdef SCENE_SPOT_LIGHT_COUNT - SpotLight spotLight; - for( int i = 0; i < SCENE_SPOT_LIGHT_COUNT; i++) { - if(!isRendererCulledByLight(renderer_Layer.xy, scene_SpotLightCullingMask[i])){ - spotLight.color = scene_SpotLightColor[i]; - spotLight.position = scene_SpotLightPosition[i]; - spotLight.direction = scene_SpotLightDirection[i]; - spotLight.distance = scene_SpotLightDistance[i]; - spotLight.angleCos = scene_SpotLightAngleCos[i]; - spotLight.penumbraCos = scene_SpotLightPenumbraCos[i]; - - vec3 direction = spotLight.position - v_pos; - float lightDistance = length( direction ); - direction /= lightDistance; - float angleCos = dot( direction, -spotLight.direction ); - float decay = clamp(1.0 - pow(lightDistance/spotLight.distance, 4.0), 0.0, 1.0); - float spotEffect = smoothstep( spotLight.penumbraCos, spotLight.angleCos, angleCos ); - float decayTotal = decay * spotEffect; - float d = max( dot( N, direction ), 0.0 ) * decayTotal; - lightDiffuse += spotLight.color * d; - - vec3 halfDir = normalize( V + direction ); - float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess ) * decayTotal; - lightSpecular += spotLight.color * s; - } - } - - #endif - - diffuse *= vec4( lightDiffuse, 1.0 ); - specular *= vec4( lightSpecular, 1.0 ); - - #ifdef MATERIAL_IS_ALPHA_CUTOFF - if( diffuse.a < material_AlphaCutoff ) { - discard; - } - #endif diff --git a/packages/core/src/shaderlib/mobile_material_frag.glsl b/packages/core/src/shaderlib/mobile_material_frag.glsl deleted file mode 100644 index 369814f72c..0000000000 --- a/packages/core/src/shaderlib/mobile_material_frag.glsl +++ /dev/null @@ -1,22 +0,0 @@ -uniform vec4 material_EmissiveColor; -uniform vec4 material_BaseColor; -uniform vec4 material_SpecularColor; -uniform float material_Shininess; -uniform float material_NormalIntensity; -uniform float material_AlphaCutoff; - -#ifdef MATERIAL_HAS_EMISSIVETEXTURE - uniform sampler2D material_EmissiveTexture; -#endif - -#ifdef MATERIAL_HAS_BASETEXTURE - uniform sampler2D material_BaseTexture; -#endif - -#ifdef MATERIAL_HAS_SPECULAR_TEXTURE - uniform sampler2D material_SpecularTexture; -#endif - -#ifdef MATERIAL_HAS_NORMALTEXTURE - uniform sampler2D material_NormalTexture; -#endif diff --git a/packages/core/src/shaderlib/noise_cellular.glsl b/packages/core/src/shaderlib/noise_cellular.glsl deleted file mode 100644 index 68c14f877d..0000000000 --- a/packages/core/src/shaderlib/noise_cellular.glsl +++ /dev/null @@ -1,4 +0,0 @@ -#include -#include -#include -#include diff --git a/packages/core/src/shaderlib/noise_cellular_2D.glsl b/packages/core/src/shaderlib/noise_cellular_2D.glsl deleted file mode 100644 index 5374bb7983..0000000000 --- a/packages/core/src/shaderlib/noise_cellular_2D.glsl +++ /dev/null @@ -1,48 +0,0 @@ - -// Cellular noise ("Worley noise") in 2D in GLSL. -// Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved. -// This code is released under the conditions of the MIT license. -// See LICENSE file for details. -// https://github.com/stegu/webgl-noise - -// Cellular noise, returning F1 and F2 in a vec2. -// Standard 3x3 search window for good F1 and F2 values -vec2 cellular( vec2 P ) { - - vec2 Pi = mod289( floor( P ) ); - vec2 Pf = fract( P ); - vec3 oi = vec3( -1.0, 0.0, 1.0); - vec3 of = vec3( -0.5, 0.5, 1.5); - vec3 px = permute( Pi.x + oi ); - vec3 p = permute( px.x + Pi.y + oi ); // p11, p12, p13 - vec3 ox = fract( p * K ) - Ko; - vec3 oy = mod7( floor( p * K ) ) * K - Ko; - vec3 dx = Pf.x + 0.5 + jitter * ox; - vec3 dy = Pf.y - of + jitter * oy; - vec3 d1 = dx * dx + dy * dy; // d11, d12 and d13, squared - p = permute( px.y + Pi.y + oi ); // p21, p22, p23 - ox = fract( p * K ) - Ko; - oy = mod7( floor( p * K ) ) * K - Ko; - dx = Pf.x - 0.5 + jitter * ox; - dy = Pf.y - of + jitter * oy; - vec3 d2 = dx * dx + dy * dy; // d21, d22 and d23, squared - p = permute( px.z + Pi.y + oi ); // p31, p32, p33 - ox = fract( p * K ) - Ko; - oy = mod7( floor( p * K ) ) * K - Ko; - dx = Pf.x - 1.5 + jitter * ox; - dy = Pf.y - of + jitter * oy; - vec3 d3 = dx * dx + dy * dy; // d31, d32 and d33, squared - // Sort out the two smallest distances (F1, F2) - vec3 d1a = min( d1, d2 ); - d2 = max( d1, d2 ); // Swap to keep candidates for F2 - d2 = min( d2, d3 ); // neither F1 nor F2 are now in d3 - d1 = min( d1a, d2 ); // F1 is now in d1 - d2 = max( d1a, d2 ); // Swap to keep candidates for F2 - d1.xy = ( d1.x < d1.y ) ? d1.xy : d1.yx; // Swap if smaller - d1.xz = ( d1.x < d1.z ) ? d1.xz : d1.zx; // F1 is in d1.x - d1.yz = min( d1.yz, d2.yz ); // F2 is now not in d2.yz - d1.y = min( d1.y, d1.z ); // nor in d1.z - d1.y = min( d1.y, d2.x ); // F2 is in d1.y, we're done. - return sqrt( d1.xy ); - -} diff --git a/packages/core/src/shaderlib/noise_cellular_2x2.glsl b/packages/core/src/shaderlib/noise_cellular_2x2.glsl deleted file mode 100644 index c6608178d7..0000000000 --- a/packages/core/src/shaderlib/noise_cellular_2x2.glsl +++ /dev/null @@ -1,36 +0,0 @@ - -// Cellular noise ("Worley noise") in 2D in GLSL. -// Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved. -// This code is released under the conditions of the MIT license. -// See LICENSE file for details. -// https://github.com/stegu/webgl-noise - -// Cellular noise, returning F1 and F2 in a vec2. -// Speeded up by using 2x2 search window instead of 3x3, -// at the expense of some strong pattern artifacts. -// F2 is often wrong and has sharp discontinuities. -// If you need a smooth F2, use the slower 3x3 version. -// F1 is sometimes wrong, too, but OK for most purposes. -vec2 cellular2x2( vec2 P ) { - - vec2 Pi = mod289( floor( P ) ); - vec2 Pf = fract( P ); - vec4 Pfx = Pf.x + vec4( -0.5, -1.5, -0.5, -1.5 ); - vec4 Pfy = Pf.y + vec4( -0.5, -0.5, -1.5, -1.5 ); - vec4 p = permute( Pi.x + vec4( 0.0, 1.0, 0.0, 1.0 ) ); - p = permute( p + Pi.y + vec4( 0.0, 0.0, 1.0, 1.0 ) ); - vec4 ox = mod7( p ) * K + Kd2; - vec4 oy = mod7( floor( p * K ) ) * K + Kd2; - vec4 dx = Pfx + jitter1 * ox; - vec4 dy = Pfy + jitter1 * oy; - vec4 d = dx * dx + dy * dy; // d11, d12, d21 and d22, squared - - // Do it right and find both F1 and F2 - d.xy = ( d.x < d.y ) ? d.xy : d.yx; // Swap if smaller - d.xz = ( d.x < d.z ) ? d.xz : d.zx; - d.xw = ( d.x < d.w ) ? d.xw : d.wx; - d.y = min( d.y, d.z ); - d.y = min( d.y, d.w ); - return sqrt( d.xy ); - -} diff --git a/packages/core/src/shaderlib/noise_cellular_2x2x2.glsl b/packages/core/src/shaderlib/noise_cellular_2x2x2.glsl deleted file mode 100644 index d5840c9b84..0000000000 --- a/packages/core/src/shaderlib/noise_cellular_2x2x2.glsl +++ /dev/null @@ -1,50 +0,0 @@ - -// Cellular noise ("Worley noise") in 3D in GLSL. -// Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved. -// This code is released under the conditions of the MIT license. -// See LICENSE file for details. -// https://github.com/stegu/webgl-noise - -// Cellular noise, returning F1 and F2 in a vec2. -// Speeded up by using 2x2x2 search window instead of 3x3x3, -// at the expense of some pattern artifacts. -// F2 is often wrong and has sharp discontinuities. -// If you need a good F2, use the slower 3x3x3 version. -vec2 cellular2x2x2(vec3 P) { - - vec3 Pi = mod289( floor( P ) ); - vec3 Pf = fract( P ); - vec4 Pfx = Pf.x + vec4( 0.0, -1.0, 0.0, -1.0 ); - vec4 Pfy = Pf.y + vec4( 0.0, 0.0, -1.0, -1.0 ); - vec4 p = permute( Pi.x + vec4( 0.0, 1.0, 0.0, 1.0 ) ); - p = permute( p + Pi.y + vec4( 0.0, 0.0, 1.0, 1.0 ) ); - vec4 p1 = permute( p + Pi.z ); // z+0 - vec4 p2 = permute( p + Pi.z + vec4( 1.0 ) ); // z+1 - vec4 ox1 = fract( p1 * K ) - Ko; - vec4 oy1 = mod7( floor( p1 * K ) ) * K - Ko; - vec4 oz1 = floor( p1 * K2 ) * Kz - Kzo; // p1 < 289 guaranteed - vec4 ox2 = fract( p2 * K ) - Ko; - vec4 oy2 = mod7( floor( p2 * K ) ) * K - Ko; - vec4 oz2 = floor( p2 * K2 ) * Kz - Kzo; - vec4 dx1 = Pfx + jitter1 * ox1; - vec4 dy1 = Pfy + jitter1 * oy1; - vec4 dz1 = Pf.z + jitter1 * oz1; - vec4 dx2 = Pfx + jitter1 * ox2; - vec4 dy2 = Pfy + jitter1 * oy2; - vec4 dz2 = Pf.z - 1.0 + jitter1 * oz2; - vec4 d1 = dx1 * dx1 + dy1 * dy1 + dz1 * dz1; // z+0 - vec4 d2 = dx2 * dx2 + dy2 * dy2 + dz2 * dz2; // z+1 - - // Do it right and sort out both F1 and F2 - vec4 d = min( d1, d2 ); // F1 is now in d - d2 = max( d1, d2 ); // Make sure we keep all candidates for F2 - d.xy = ( d.x < d.y ) ? d.xy : d.yx; // Swap smallest to d.x - d.xz = ( d.x < d.z ) ? d.xz : d.zx; - d.xw = ( d.x < d.w ) ? d.xw : d.wx; // F1 is now in d.x - d.yzw = min( d.yzw, d2.yzw ); // F2 now not in d2.yzw - d.y = min( d.y, d.z ); // nor in d.z - d.y = min( d.y, d.w ); // nor in d.w - d.y = min( d.y, d2.x ); // F2 is now in d.y - return sqrt( d.xy ); // F1 and F2 - -} diff --git a/packages/core/src/shaderlib/noise_cellular_3D.glsl b/packages/core/src/shaderlib/noise_cellular_3D.glsl deleted file mode 100644 index 473f679ce2..0000000000 --- a/packages/core/src/shaderlib/noise_cellular_3D.glsl +++ /dev/null @@ -1,155 +0,0 @@ - -// Cellular noise ("Worley noise") in 3D in GLSL. -// Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved. -// This code is released under the conditions of the MIT license. -// See LICENSE file for details. -// https://github.com/stegu/webgl-noise - -// Cellular noise, returning F1 and F2 in a vec2. -// 3x3x3 search region for good F2 everywhere, but a lot -// slower than the 2x2x2 version. -// The code below is a bit scary even to its author, -// but it has at least half decent performance on a -// modern GPU. In any case, it beats any software -// implementation of Worley noise hands down. - -vec2 cellular( vec3 P ) { - - vec3 Pi = mod289( floor( P ) ); - vec3 Pf = fract( P ) - 0.5; - - vec3 Pfx = Pf.x + vec3( 1.0, 0.0, -1.0 ); - vec3 Pfy = Pf.y + vec3( 1.0, 0.0, -1.0 ); - vec3 Pfz = Pf.z + vec3( 1.0, 0.0, -1.0 ); - - vec3 p = permute( Pi.x + vec3( -1.0, 0.0, 1.0 ) ); - vec3 p1 = permute( p + Pi.y - 1.0 ); - vec3 p2 = permute( p + Pi.y ); - vec3 p3 = permute( p + Pi.y + 1.0 ); - - vec3 p11 = permute( p1 + Pi.z - 1.0 ); - vec3 p12 = permute( p1 + Pi.z ); - vec3 p13 = permute( p1 + Pi.z + 1.0 ); - - vec3 p21 = permute( p2 + Pi.z - 1.0 ); - vec3 p22 = permute( p2 + Pi.z ); - vec3 p23 = permute( p2 + Pi.z + 1.0 ); - - vec3 p31 = permute( p3 + Pi.z - 1.0 ); - vec3 p32 = permute( p3 + Pi.z ); - vec3 p33 = permute( p3 + Pi.z + 1.0 ); - - vec3 ox11 = fract( p11 * K ) - Ko; - vec3 oy11 = mod7( floor( p11 * K ) ) * K - Ko; - vec3 oz11 = floor( p11 * K2 ) * Kz - Kzo; // p11 < 289 guaranteed - - vec3 ox12 = fract( p12 * K ) - Ko; - vec3 oy12 = mod7( floor( p12 * K ) ) * K - Ko; - vec3 oz12 = floor( p12 * K2 ) * Kz - Kzo; - - vec3 ox13 = fract( p13 * K ) - Ko; - vec3 oy13 = mod7( floor( p13 * K ) ) * K - Ko; - vec3 oz13 = floor( p13 * K2 ) * Kz - Kzo; - - vec3 ox21 = fract( p21 * K ) - Ko; - vec3 oy21 = mod7( floor( p21 * K ) ) * K - Ko; - vec3 oz21 = floor( p21 * K2 ) * Kz - Kzo; - - vec3 ox22 = fract( p22 * K ) - Ko; - vec3 oy22 = mod7( floor( p22 * K ) ) * K - Ko; - vec3 oz22 = floor( p22 * K2 ) * Kz - Kzo; - - vec3 ox23 = fract( p23 * K ) - Ko; - vec3 oy23 = mod7( floor( p23 * K ) ) * K - Ko; - vec3 oz23 = floor( p23 * K2 ) * Kz - Kzo; - - vec3 ox31 = fract( p31 * K ) - Ko; - vec3 oy31 = mod7( floor( p31 * K ) ) * K - Ko; - vec3 oz31 = floor( p31 * K2 ) * Kz - Kzo; - - vec3 ox32 = fract( p32 * K ) - Ko; - vec3 oy32 = mod7( floor( p32 * K ) ) * K - Ko; - vec3 oz32 = floor( p32 * K2 ) * Kz - Kzo; - - vec3 ox33 = fract( p33 * K ) - Ko; - vec3 oy33 = mod7( floor( p33 * K ) ) * K - Ko; - vec3 oz33 = floor( p33 * K2 ) * Kz - Kzo; - - vec3 dx11 = Pfx + jitter * ox11; - vec3 dy11 = Pfy.x + jitter * oy11; - vec3 dz11 = Pfz.x + jitter * oz11; - - vec3 dx12 = Pfx + jitter * ox12; - vec3 dy12 = Pfy.x + jitter * oy12; - vec3 dz12 = Pfz.y + jitter * oz12; - - vec3 dx13 = Pfx + jitter * ox13; - vec3 dy13 = Pfy.x + jitter * oy13; - vec3 dz13 = Pfz.z + jitter * oz13; - - vec3 dx21 = Pfx + jitter * ox21; - vec3 dy21 = Pfy.y + jitter * oy21; - vec3 dz21 = Pfz.x + jitter * oz21; - - vec3 dx22 = Pfx + jitter * ox22; - vec3 dy22 = Pfy.y + jitter * oy22; - vec3 dz22 = Pfz.y + jitter * oz22; - - vec3 dx23 = Pfx + jitter * ox23; - vec3 dy23 = Pfy.y + jitter * oy23; - vec3 dz23 = Pfz.z + jitter * oz23; - - vec3 dx31 = Pfx + jitter * ox31; - vec3 dy31 = Pfy.z + jitter * oy31; - vec3 dz31 = Pfz.x + jitter * oz31; - - vec3 dx32 = Pfx + jitter * ox32; - vec3 dy32 = Pfy.z + jitter * oy32; - vec3 dz32 = Pfz.y + jitter * oz32; - - vec3 dx33 = Pfx + jitter * ox33; - vec3 dy33 = Pfy.z + jitter * oy33; - vec3 dz33 = Pfz.z + jitter * oz33; - - vec3 d11 = dx11 * dx11 + dy11 * dy11 + dz11 * dz11; - vec3 d12 = dx12 * dx12 + dy12 * dy12 + dz12 * dz12; - vec3 d13 = dx13 * dx13 + dy13 * dy13 + dz13 * dz13; - vec3 d21 = dx21 * dx21 + dy21 * dy21 + dz21 * dz21; - vec3 d22 = dx22 * dx22 + dy22 * dy22 + dz22 * dz22; - vec3 d23 = dx23 * dx23 + dy23 * dy23 + dz23 * dz23; - vec3 d31 = dx31 * dx31 + dy31 * dy31 + dz31 * dz31; - vec3 d32 = dx32 * dx32 + dy32 * dy32 + dz32 * dz32; - vec3 d33 = dx33 * dx33 + dy33 * dy33 + dz33 * dz33; - - // Do it right and sort out both F1 and F2 - vec3 d1a = min( d11, d12 ); - d12 = max( d11, d12 ); - d11 = min( d1a, d13 ); // Smallest now not in d12 or d13 - d13 = max( d1a, d13 ); - d12 = min( d12, d13 ); // 2nd smallest now not in d13 - vec3 d2a = min( d21, d22 ); - d22 = max( d21, d22 ); - d21 = min( d2a, d23 ); // Smallest now not in d22 or d23 - d23 = max( d2a, d23 ); - d22 = min( d22, d23 ); // 2nd smallest now not in d23 - vec3 d3a = min( d31, d32 ); - d32 = max( d31, d32 ); - d31 = min( d3a, d33 ); // Smallest now not in d32 or d33 - d33 = max( d3a, d33 ); - d32 = min( d32, d33 ); // 2nd smallest now not in d33 - vec3 da = min( d11, d21 ); - d21 = max( d11, d21 ); - d11 = min( da, d31 ); // Smallest now in d11 - d31 = max( da, d31 ); // 2nd smallest now not in d31 - d11.xy = ( d11.x < d11.y ) ? d11.xy : d11.yx; - d11.xz = ( d11.x < d11.z ) ? d11.xz : d11.zx; // d11.x now smallest - d12 = min( d12, d21 ); // 2nd smallest now not in d21 - d12 = min( d12, d22 ); // nor in d22 - d12 = min( d12, d31 ); // nor in d31 - d12 = min( d12, d32 ); // nor in d32 - d11.yz = min( d11.yz, d12.xy ); // nor in d12.yz - d11.y = min( d11.y, d12.z ); // Only two more to go - d11.y = min( d11.y, d11.z ); // Done! (Phew! ) - return sqrt( d11.xy ); // F1, F2 - -} diff --git a/packages/core/src/shaderlib/noise_perlin.glsl b/packages/core/src/shaderlib/noise_perlin.glsl deleted file mode 100644 index 09522bf20a..0000000000 --- a/packages/core/src/shaderlib/noise_perlin.glsl +++ /dev/null @@ -1,3 +0,0 @@ -#include -#include -#include diff --git a/packages/core/src/shaderlib/noise_perlin_2D.glsl b/packages/core/src/shaderlib/noise_perlin_2D.glsl deleted file mode 100644 index 9a953fd734..0000000000 --- a/packages/core/src/shaderlib/noise_perlin_2D.glsl +++ /dev/null @@ -1,96 +0,0 @@ -// -// GLSL textureless classic 2D noise "cnoise", -// with an RSL-style periodic variant "pnoise". -// Author: Stefan Gustavson (stefan.gustavson@liu.se) -// Version: 2011-08-22 -// -// Many thanks to Ian McEwan of Ashima Arts for the -// ideas for permutation and gradient selection. -// -// Copyright (c) 2011 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/stegu/webgl-noise -// - -// Classic Perlin noise -float perlin( vec2 P ) { - - vec4 Pi = floor(P.xyxy) + vec4(0.0, 0.0, 1.0, 1.0); - vec4 Pf = fract(P.xyxy) - vec4(0.0, 0.0, 1.0, 1.0); - Pi = mod289(Pi); // To avoid truncation effects in permutation - vec4 ix = Pi.xzxz; - vec4 iy = Pi.yyww; - vec4 fx = Pf.xzxz; - vec4 fy = Pf.yyww; - - vec4 i = permute(permute(ix) + iy); - - vec4 gx = fract(i * (1.0 / 41.0)) * 2.0 - 1.0 ; - vec4 gy = abs(gx) - 0.5 ; - vec4 tx = floor(gx + 0.5); - gx = gx - tx; - - vec2 g00 = vec2(gx.x,gy.x); - vec2 g10 = vec2(gx.y,gy.y); - vec2 g01 = vec2(gx.z,gy.z); - vec2 g11 = vec2(gx.w,gy.w); - - vec4 norm = taylorInvSqrt(vec4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); - g00 *= norm.x; - g01 *= norm.y; - g10 *= norm.z; - g11 *= norm.w; - - float n00 = dot(g00, vec2(fx.x, fy.x)); - float n10 = dot(g10, vec2(fx.y, fy.y)); - float n01 = dot(g01, vec2(fx.z, fy.z)); - float n11 = dot(g11, vec2(fx.w, fy.w)); - - vec2 fade_xy = fade(Pf.xy); - vec2 n_x = mix(vec2(n00, n01), vec2(n10, n11), fade_xy.x); - float n_xy = mix(n_x.x, n_x.y, fade_xy.y); - return 2.3 * n_xy; - -} - -// Classic Perlin noise, periodic variant -float perlin( vec2 P, vec2 rep ) { - - vec4 Pi = floor(P.xyxy) + vec4(0.0, 0.0, 1.0, 1.0); - vec4 Pf = fract(P.xyxy) - vec4(0.0, 0.0, 1.0, 1.0); - Pi = mod(Pi, rep.xyxy); // To create noise with explicit period - Pi = mod289(Pi); // To avoid truncation effects in permutation - vec4 ix = Pi.xzxz; - vec4 iy = Pi.yyww; - vec4 fx = Pf.xzxz; - vec4 fy = Pf.yyww; - - vec4 i = permute(permute(ix) + iy); - - vec4 gx = fract(i * (1.0 / 41.0)) * 2.0 - 1.0 ; - vec4 gy = abs(gx) - 0.5 ; - vec4 tx = floor(gx + 0.5); - gx = gx - tx; - - vec2 g00 = vec2(gx.x,gy.x); - vec2 g10 = vec2(gx.y,gy.y); - vec2 g01 = vec2(gx.z,gy.z); - vec2 g11 = vec2(gx.w,gy.w); - - vec4 norm = taylorInvSqrt(vec4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); - g00 *= norm.x; - g01 *= norm.y; - g10 *= norm.z; - g11 *= norm.w; - - float n00 = dot(g00, vec2(fx.x, fy.x)); - float n10 = dot(g10, vec2(fx.y, fy.y)); - float n01 = dot(g01, vec2(fx.z, fy.z)); - float n11 = dot(g11, vec2(fx.w, fy.w)); - - vec2 fade_xy = fade(Pf.xy); - vec2 n_x = mix(vec2(n00, n01), vec2(n10, n11), fade_xy.x); - float n_xy = mix(n_x.x, n_x.y, fade_xy.y); - return 2.3 * n_xy; - -} diff --git a/packages/core/src/shaderlib/noise_perlin_3D.glsl b/packages/core/src/shaderlib/noise_perlin_3D.glsl deleted file mode 100644 index f48c4e11bc..0000000000 --- a/packages/core/src/shaderlib/noise_perlin_3D.glsl +++ /dev/null @@ -1,155 +0,0 @@ -// -// GLSL textureless classic 3D noise "cnoise", -// with an RSL-style periodic variant "pnoise". -// Author: Stefan Gustavson (stefan.gustavson@liu.se) -// Version: 2011-10-11 -// -// Many thanks to Ian McEwan of Ashima Arts for the -// ideas for permutation and gradient selection. -// -// Copyright (c) 2011 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/stegu/webgl-noise -// - -// Classic Perlin noise -float perlin( vec3 P ) { - - vec3 Pi0 = floor(P); // Integer part for indexing - vec3 Pi1 = Pi0 + vec3(1.0); // Integer part + 1 - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - vec3 Pf0 = fract(P); // Fractional part for interpolation - vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0 - vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - vec4 iy = vec4(Pi0.yy, Pi1.yy); - vec4 iz0 = Pi0.zzzz; - vec4 iz1 = Pi1.zzzz; - - vec4 ixy = permute(permute(ix) + iy); - vec4 ixy0 = permute(ixy + iz0); - vec4 ixy1 = permute(ixy + iz1); - - vec4 gx0 = ixy0 * (1.0 / 7.0); - vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5; - gx0 = fract(gx0); - vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0); - vec4 sz0 = step(gz0, vec4(0.0)); - gx0 -= sz0 * (step(0.0, gx0) - 0.5); - gy0 -= sz0 * (step(0.0, gy0) - 0.5); - - vec4 gx1 = ixy1 * (1.0 / 7.0); - vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5; - gx1 = fract(gx1); - vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1); - vec4 sz1 = step(gz1, vec4(0.0)); - gx1 -= sz1 * (step(0.0, gx1) - 0.5); - gy1 -= sz1 * (step(0.0, gy1) - 0.5); - - vec3 g000 = vec3(gx0.x,gy0.x,gz0.x); - vec3 g100 = vec3(gx0.y,gy0.y,gz0.y); - vec3 g010 = vec3(gx0.z,gy0.z,gz0.z); - vec3 g110 = vec3(gx0.w,gy0.w,gz0.w); - vec3 g001 = vec3(gx1.x,gy1.x,gz1.x); - vec3 g101 = vec3(gx1.y,gy1.y,gz1.y); - vec3 g011 = vec3(gx1.z,gy1.z,gz1.z); - vec3 g111 = vec3(gx1.w,gy1.w,gz1.w); - - vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); - g000 *= norm0.x; - g010 *= norm0.y; - g100 *= norm0.z; - g110 *= norm0.w; - vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); - g001 *= norm1.x; - g011 *= norm1.y; - g101 *= norm1.z; - g111 *= norm1.w; - - float n000 = dot(g000, Pf0); - float n100 = dot(g100, vec3(Pf1.x, Pf0.yz)); - float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z)); - float n110 = dot(g110, vec3(Pf1.xy, Pf0.z)); - float n001 = dot(g001, vec3(Pf0.xy, Pf1.z)); - float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z)); - float n011 = dot(g011, vec3(Pf0.x, Pf1.yz)); - float n111 = dot(g111, Pf1); - - vec3 fade_xyz = fade(Pf0); - vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z); - vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y); - float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x); - return 2.2 * n_xyz; - -} - -// Classic Perlin noise, periodic variant -float perlin( vec3 P, vec3 rep ) { - - vec3 Pi0 = mod(floor(P), rep); // Integer part, modulo period - vec3 Pi1 = mod(Pi0 + vec3(1.0), rep); // Integer part + 1, mod period - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - vec3 Pf0 = fract(P); // Fractional part for interpolation - vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0 - vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - vec4 iy = vec4(Pi0.yy, Pi1.yy); - vec4 iz0 = Pi0.zzzz; - vec4 iz1 = Pi1.zzzz; - - vec4 ixy = permute(permute(ix) + iy); - vec4 ixy0 = permute(ixy + iz0); - vec4 ixy1 = permute(ixy + iz1); - - vec4 gx0 = ixy0 * (1.0 / 7.0); - vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5; - gx0 = fract(gx0); - vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0); - vec4 sz0 = step(gz0, vec4(0.0)); - gx0 -= sz0 * (step(0.0, gx0) - 0.5); - gy0 -= sz0 * (step(0.0, gy0) - 0.5); - - vec4 gx1 = ixy1 * (1.0 / 7.0); - vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5; - gx1 = fract(gx1); - vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1); - vec4 sz1 = step(gz1, vec4(0.0)); - gx1 -= sz1 * (step(0.0, gx1) - 0.5); - gy1 -= sz1 * (step(0.0, gy1) - 0.5); - - vec3 g000 = vec3(gx0.x,gy0.x,gz0.x); - vec3 g100 = vec3(gx0.y,gy0.y,gz0.y); - vec3 g010 = vec3(gx0.z,gy0.z,gz0.z); - vec3 g110 = vec3(gx0.w,gy0.w,gz0.w); - vec3 g001 = vec3(gx1.x,gy1.x,gz1.x); - vec3 g101 = vec3(gx1.y,gy1.y,gz1.y); - vec3 g011 = vec3(gx1.z,gy1.z,gz1.z); - vec3 g111 = vec3(gx1.w,gy1.w,gz1.w); - - vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); - g000 *= norm0.x; - g010 *= norm0.y; - g100 *= norm0.z; - g110 *= norm0.w; - vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); - g001 *= norm1.x; - g011 *= norm1.y; - g101 *= norm1.z; - g111 *= norm1.w; - - float n000 = dot(g000, Pf0); - float n100 = dot(g100, vec3(Pf1.x, Pf0.yz)); - float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z)); - float n110 = dot(g110, vec3(Pf1.xy, Pf0.z)); - float n001 = dot(g001, vec3(Pf0.xy, Pf1.z)); - float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z)); - float n011 = dot(g011, vec3(Pf0.x, Pf1.yz)); - float n111 = dot(g111, Pf1); - - vec3 fade_xyz = fade(Pf0); - vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z); - vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y); - float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x); - return 2.2 * n_xyz; - -} diff --git a/packages/core/src/shaderlib/noise_perlin_4D.glsl b/packages/core/src/shaderlib/noise_perlin_4D.glsl deleted file mode 100644 index dee47bb902..0000000000 --- a/packages/core/src/shaderlib/noise_perlin_4D.glsl +++ /dev/null @@ -1,285 +0,0 @@ -// -// GLSL textureless classic 4D noise "cnoise", -// with an RSL-style periodic variant "pnoise". -// Author: Stefan Gustavson (stefan.gustavson@liu.se) -// Version: 2011-08-22 -// -// Many thanks to Ian McEwan of Ashima Arts for the -// ideas for permutation and gradient selection. -// -// Copyright (c) 2011 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/stegu/webgl-noise -// - -// Classic Perlin noise -float perlin( vec4 P ) { - - vec4 Pi0 = floor(P); // Integer part for indexing - vec4 Pi1 = Pi0 + 1.0; // Integer part + 1 - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - vec4 Pf0 = fract(P); // Fractional part for interpolation - vec4 Pf1 = Pf0 - 1.0; // Fractional part - 1.0 - vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - vec4 iy = vec4(Pi0.yy, Pi1.yy); - vec4 iz0 = vec4(Pi0.zzzz); - vec4 iz1 = vec4(Pi1.zzzz); - vec4 iw0 = vec4(Pi0.wwww); - vec4 iw1 = vec4(Pi1.wwww); - - vec4 ixy = permute(permute(ix) + iy); - vec4 ixy0 = permute(ixy + iz0); - vec4 ixy1 = permute(ixy + iz1); - vec4 ixy00 = permute(ixy0 + iw0); - vec4 ixy01 = permute(ixy0 + iw1); - vec4 ixy10 = permute(ixy1 + iw0); - vec4 ixy11 = permute(ixy1 + iw1); - - vec4 gx00 = ixy00 * (1.0 / 7.0); - vec4 gy00 = floor(gx00) * (1.0 / 7.0); - vec4 gz00 = floor(gy00) * (1.0 / 6.0); - gx00 = fract(gx00) - 0.5; - gy00 = fract(gy00) - 0.5; - gz00 = fract(gz00) - 0.5; - vec4 gw00 = vec4(0.75) - abs(gx00) - abs(gy00) - abs(gz00); - vec4 sw00 = step(gw00, vec4(0.0)); - gx00 -= sw00 * (step(0.0, gx00) - 0.5); - gy00 -= sw00 * (step(0.0, gy00) - 0.5); - - vec4 gx01 = ixy01 * (1.0 / 7.0); - vec4 gy01 = floor(gx01) * (1.0 / 7.0); - vec4 gz01 = floor(gy01) * (1.0 / 6.0); - gx01 = fract(gx01) - 0.5; - gy01 = fract(gy01) - 0.5; - gz01 = fract(gz01) - 0.5; - vec4 gw01 = vec4(0.75) - abs(gx01) - abs(gy01) - abs(gz01); - vec4 sw01 = step(gw01, vec4(0.0)); - gx01 -= sw01 * (step(0.0, gx01) - 0.5); - gy01 -= sw01 * (step(0.0, gy01) - 0.5); - - vec4 gx10 = ixy10 * (1.0 / 7.0); - vec4 gy10 = floor(gx10) * (1.0 / 7.0); - vec4 gz10 = floor(gy10) * (1.0 / 6.0); - gx10 = fract(gx10) - 0.5; - gy10 = fract(gy10) - 0.5; - gz10 = fract(gz10) - 0.5; - vec4 gw10 = vec4(0.75) - abs(gx10) - abs(gy10) - abs(gz10); - vec4 sw10 = step(gw10, vec4(0.0)); - gx10 -= sw10 * (step(0.0, gx10) - 0.5); - gy10 -= sw10 * (step(0.0, gy10) - 0.5); - - vec4 gx11 = ixy11 * (1.0 / 7.0); - vec4 gy11 = floor(gx11) * (1.0 / 7.0); - vec4 gz11 = floor(gy11) * (1.0 / 6.0); - gx11 = fract(gx11) - 0.5; - gy11 = fract(gy11) - 0.5; - gz11 = fract(gz11) - 0.5; - vec4 gw11 = vec4(0.75) - abs(gx11) - abs(gy11) - abs(gz11); - vec4 sw11 = step(gw11, vec4(0.0)); - gx11 -= sw11 * (step(0.0, gx11) - 0.5); - gy11 -= sw11 * (step(0.0, gy11) - 0.5); - - vec4 g0000 = vec4(gx00.x,gy00.x,gz00.x,gw00.x); - vec4 g1000 = vec4(gx00.y,gy00.y,gz00.y,gw00.y); - vec4 g0100 = vec4(gx00.z,gy00.z,gz00.z,gw00.z); - vec4 g1100 = vec4(gx00.w,gy00.w,gz00.w,gw00.w); - vec4 g0010 = vec4(gx10.x,gy10.x,gz10.x,gw10.x); - vec4 g1010 = vec4(gx10.y,gy10.y,gz10.y,gw10.y); - vec4 g0110 = vec4(gx10.z,gy10.z,gz10.z,gw10.z); - vec4 g1110 = vec4(gx10.w,gy10.w,gz10.w,gw10.w); - vec4 g0001 = vec4(gx01.x,gy01.x,gz01.x,gw01.x); - vec4 g1001 = vec4(gx01.y,gy01.y,gz01.y,gw01.y); - vec4 g0101 = vec4(gx01.z,gy01.z,gz01.z,gw01.z); - vec4 g1101 = vec4(gx01.w,gy01.w,gz01.w,gw01.w); - vec4 g0011 = vec4(gx11.x,gy11.x,gz11.x,gw11.x); - vec4 g1011 = vec4(gx11.y,gy11.y,gz11.y,gw11.y); - vec4 g0111 = vec4(gx11.z,gy11.z,gz11.z,gw11.z); - vec4 g1111 = vec4(gx11.w,gy11.w,gz11.w,gw11.w); - - vec4 norm00 = taylorInvSqrt(vec4(dot(g0000, g0000), dot(g0100, g0100), dot(g1000, g1000), dot(g1100, g1100))); - g0000 *= norm00.x; - g0100 *= norm00.y; - g1000 *= norm00.z; - g1100 *= norm00.w; - - vec4 norm01 = taylorInvSqrt(vec4(dot(g0001, g0001), dot(g0101, g0101), dot(g1001, g1001), dot(g1101, g1101))); - g0001 *= norm01.x; - g0101 *= norm01.y; - g1001 *= norm01.z; - g1101 *= norm01.w; - - vec4 norm10 = taylorInvSqrt(vec4(dot(g0010, g0010), dot(g0110, g0110), dot(g1010, g1010), dot(g1110, g1110))); - g0010 *= norm10.x; - g0110 *= norm10.y; - g1010 *= norm10.z; - g1110 *= norm10.w; - - vec4 norm11 = taylorInvSqrt(vec4(dot(g0011, g0011), dot(g0111, g0111), dot(g1011, g1011), dot(g1111, g1111))); - g0011 *= norm11.x; - g0111 *= norm11.y; - g1011 *= norm11.z; - g1111 *= norm11.w; - - float n0000 = dot(g0000, Pf0); - float n1000 = dot(g1000, vec4(Pf1.x, Pf0.yzw)); - float n0100 = dot(g0100, vec4(Pf0.x, Pf1.y, Pf0.zw)); - float n1100 = dot(g1100, vec4(Pf1.xy, Pf0.zw)); - float n0010 = dot(g0010, vec4(Pf0.xy, Pf1.z, Pf0.w)); - float n1010 = dot(g1010, vec4(Pf1.x, Pf0.y, Pf1.z, Pf0.w)); - float n0110 = dot(g0110, vec4(Pf0.x, Pf1.yz, Pf0.w)); - float n1110 = dot(g1110, vec4(Pf1.xyz, Pf0.w)); - float n0001 = dot(g0001, vec4(Pf0.xyz, Pf1.w)); - float n1001 = dot(g1001, vec4(Pf1.x, Pf0.yz, Pf1.w)); - float n0101 = dot(g0101, vec4(Pf0.x, Pf1.y, Pf0.z, Pf1.w)); - float n1101 = dot(g1101, vec4(Pf1.xy, Pf0.z, Pf1.w)); - float n0011 = dot(g0011, vec4(Pf0.xy, Pf1.zw)); - float n1011 = dot(g1011, vec4(Pf1.x, Pf0.y, Pf1.zw)); - float n0111 = dot(g0111, vec4(Pf0.x, Pf1.yzw)); - float n1111 = dot(g1111, Pf1); - - vec4 fade_xyzw = fade(Pf0); - vec4 n_0w = mix(vec4(n0000, n1000, n0100, n1100), vec4(n0001, n1001, n0101, n1101), fade_xyzw.w); - vec4 n_1w = mix(vec4(n0010, n1010, n0110, n1110), vec4(n0011, n1011, n0111, n1111), fade_xyzw.w); - vec4 n_zw = mix(n_0w, n_1w, fade_xyzw.z); - vec2 n_yzw = mix(n_zw.xy, n_zw.zw, fade_xyzw.y); - float n_xyzw = mix(n_yzw.x, n_yzw.y, fade_xyzw.x); - return 2.2 * n_xyzw; - -} - -// Classic Perlin noise, periodic version -float perlin( vec4 P, vec4 rep ) { - - vec4 Pi0 = mod(floor(P), rep); // Integer part modulo rep - vec4 Pi1 = mod(Pi0 + 1.0, rep); // Integer part + 1 mod rep - Pi0 = mod289(Pi0); - Pi1 = mod289(Pi1); - vec4 Pf0 = fract(P); // Fractional part for interpolation - vec4 Pf1 = Pf0 - 1.0; // Fractional part - 1.0 - vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); - vec4 iy = vec4(Pi0.yy, Pi1.yy); - vec4 iz0 = vec4(Pi0.zzzz); - vec4 iz1 = vec4(Pi1.zzzz); - vec4 iw0 = vec4(Pi0.wwww); - vec4 iw1 = vec4(Pi1.wwww); - - vec4 ixy = permute(permute(ix) + iy); - vec4 ixy0 = permute(ixy + iz0); - vec4 ixy1 = permute(ixy + iz1); - vec4 ixy00 = permute(ixy0 + iw0); - vec4 ixy01 = permute(ixy0 + iw1); - vec4 ixy10 = permute(ixy1 + iw0); - vec4 ixy11 = permute(ixy1 + iw1); - - vec4 gx00 = ixy00 * (1.0 / 7.0); - vec4 gy00 = floor(gx00) * (1.0 / 7.0); - vec4 gz00 = floor(gy00) * (1.0 / 6.0); - gx00 = fract(gx00) - 0.5; - gy00 = fract(gy00) - 0.5; - gz00 = fract(gz00) - 0.5; - vec4 gw00 = vec4(0.75) - abs(gx00) - abs(gy00) - abs(gz00); - vec4 sw00 = step(gw00, vec4(0.0)); - gx00 -= sw00 * (step(0.0, gx00) - 0.5); - gy00 -= sw00 * (step(0.0, gy00) - 0.5); - - vec4 gx01 = ixy01 * (1.0 / 7.0); - vec4 gy01 = floor(gx01) * (1.0 / 7.0); - vec4 gz01 = floor(gy01) * (1.0 / 6.0); - gx01 = fract(gx01) - 0.5; - gy01 = fract(gy01) - 0.5; - gz01 = fract(gz01) - 0.5; - vec4 gw01 = vec4(0.75) - abs(gx01) - abs(gy01) - abs(gz01); - vec4 sw01 = step(gw01, vec4(0.0)); - gx01 -= sw01 * (step(0.0, gx01) - 0.5); - gy01 -= sw01 * (step(0.0, gy01) - 0.5); - - vec4 gx10 = ixy10 * (1.0 / 7.0); - vec4 gy10 = floor(gx10) * (1.0 / 7.0); - vec4 gz10 = floor(gy10) * (1.0 / 6.0); - gx10 = fract(gx10) - 0.5; - gy10 = fract(gy10) - 0.5; - gz10 = fract(gz10) - 0.5; - vec4 gw10 = vec4(0.75) - abs(gx10) - abs(gy10) - abs(gz10); - vec4 sw10 = step(gw10, vec4(0.0)); - gx10 -= sw10 * (step(0.0, gx10) - 0.5); - gy10 -= sw10 * (step(0.0, gy10) - 0.5); - - vec4 gx11 = ixy11 * (1.0 / 7.0); - vec4 gy11 = floor(gx11) * (1.0 / 7.0); - vec4 gz11 = floor(gy11) * (1.0 / 6.0); - gx11 = fract(gx11) - 0.5; - gy11 = fract(gy11) - 0.5; - gz11 = fract(gz11) - 0.5; - vec4 gw11 = vec4(0.75) - abs(gx11) - abs(gy11) - abs(gz11); - vec4 sw11 = step(gw11, vec4(0.0)); - gx11 -= sw11 * (step(0.0, gx11) - 0.5); - gy11 -= sw11 * (step(0.0, gy11) - 0.5); - - vec4 g0000 = vec4(gx00.x,gy00.x,gz00.x,gw00.x); - vec4 g1000 = vec4(gx00.y,gy00.y,gz00.y,gw00.y); - vec4 g0100 = vec4(gx00.z,gy00.z,gz00.z,gw00.z); - vec4 g1100 = vec4(gx00.w,gy00.w,gz00.w,gw00.w); - vec4 g0010 = vec4(gx10.x,gy10.x,gz10.x,gw10.x); - vec4 g1010 = vec4(gx10.y,gy10.y,gz10.y,gw10.y); - vec4 g0110 = vec4(gx10.z,gy10.z,gz10.z,gw10.z); - vec4 g1110 = vec4(gx10.w,gy10.w,gz10.w,gw10.w); - vec4 g0001 = vec4(gx01.x,gy01.x,gz01.x,gw01.x); - vec4 g1001 = vec4(gx01.y,gy01.y,gz01.y,gw01.y); - vec4 g0101 = vec4(gx01.z,gy01.z,gz01.z,gw01.z); - vec4 g1101 = vec4(gx01.w,gy01.w,gz01.w,gw01.w); - vec4 g0011 = vec4(gx11.x,gy11.x,gz11.x,gw11.x); - vec4 g1011 = vec4(gx11.y,gy11.y,gz11.y,gw11.y); - vec4 g0111 = vec4(gx11.z,gy11.z,gz11.z,gw11.z); - vec4 g1111 = vec4(gx11.w,gy11.w,gz11.w,gw11.w); - - vec4 norm00 = taylorInvSqrt(vec4(dot(g0000, g0000), dot(g0100, g0100), dot(g1000, g1000), dot(g1100, g1100))); - g0000 *= norm00.x; - g0100 *= norm00.y; - g1000 *= norm00.z; - g1100 *= norm00.w; - - vec4 norm01 = taylorInvSqrt(vec4(dot(g0001, g0001), dot(g0101, g0101), dot(g1001, g1001), dot(g1101, g1101))); - g0001 *= norm01.x; - g0101 *= norm01.y; - g1001 *= norm01.z; - g1101 *= norm01.w; - - vec4 norm10 = taylorInvSqrt(vec4(dot(g0010, g0010), dot(g0110, g0110), dot(g1010, g1010), dot(g1110, g1110))); - g0010 *= norm10.x; - g0110 *= norm10.y; - g1010 *= norm10.z; - g1110 *= norm10.w; - - vec4 norm11 = taylorInvSqrt(vec4(dot(g0011, g0011), dot(g0111, g0111), dot(g1011, g1011), dot(g1111, g1111))); - g0011 *= norm11.x; - g0111 *= norm11.y; - g1011 *= norm11.z; - g1111 *= norm11.w; - - float n0000 = dot(g0000, Pf0); - float n1000 = dot(g1000, vec4(Pf1.x, Pf0.yzw)); - float n0100 = dot(g0100, vec4(Pf0.x, Pf1.y, Pf0.zw)); - float n1100 = dot(g1100, vec4(Pf1.xy, Pf0.zw)); - float n0010 = dot(g0010, vec4(Pf0.xy, Pf1.z, Pf0.w)); - float n1010 = dot(g1010, vec4(Pf1.x, Pf0.y, Pf1.z, Pf0.w)); - float n0110 = dot(g0110, vec4(Pf0.x, Pf1.yz, Pf0.w)); - float n1110 = dot(g1110, vec4(Pf1.xyz, Pf0.w)); - float n0001 = dot(g0001, vec4(Pf0.xyz, Pf1.w)); - float n1001 = dot(g1001, vec4(Pf1.x, Pf0.yz, Pf1.w)); - float n0101 = dot(g0101, vec4(Pf0.x, Pf1.y, Pf0.z, Pf1.w)); - float n1101 = dot(g1101, vec4(Pf1.xy, Pf0.z, Pf1.w)); - float n0011 = dot(g0011, vec4(Pf0.xy, Pf1.zw)); - float n1011 = dot(g1011, vec4(Pf1.x, Pf0.y, Pf1.zw)); - float n0111 = dot(g0111, vec4(Pf0.x, Pf1.yzw)); - float n1111 = dot(g1111, Pf1); - - vec4 fade_xyzw = fade(Pf0); - vec4 n_0w = mix(vec4(n0000, n1000, n0100, n1100), vec4(n0001, n1001, n0101, n1101), fade_xyzw.w); - vec4 n_1w = mix(vec4(n0010, n1010, n0110, n1110), vec4(n0011, n1011, n0111, n1111), fade_xyzw.w); - vec4 n_zw = mix(n_0w, n_1w, fade_xyzw.z); - vec2 n_yzw = mix(n_zw.xy, n_zw.zw, fade_xyzw.y); - float n_xyzw = mix(n_yzw.x, n_yzw.y, fade_xyzw.x); - return 2.2 * n_xyzw; - -} diff --git a/packages/core/src/shaderlib/noise_psrd_2D.glsl b/packages/core/src/shaderlib/noise_psrd_2D.glsl deleted file mode 100644 index 4df67ce42f..0000000000 --- a/packages/core/src/shaderlib/noise_psrd_2D.glsl +++ /dev/null @@ -1,425 +0,0 @@ -// Periodic (tiling) 2-D simplex noise (hexagonal lattice gradient noise) -// with rotating gradients and analytic derivatives. -// Variants also without the derivative (no "d" in the name), without -// the tiling property (no "p" in the name) and without the rotating -// gradients (no "r" in the name). -// -// This is (yet) another variation on simplex noise. It's similar to the -// version presented by Ken Perlin, but the grid is axis-aligned and -// slightly stretched in the y direction to permit rectangular tiling. -// -// The noise can be made to tile seamlessly to any integer period in x and -// any even integer period in y. Odd periods may be specified for y, but -// then the actual tiling period will be twice that number. -// -// The rotating gradients give the appearance of a swirling motion, and can -// serve a similar purpose for animation as motion along z in 3-D noise. -// The rotating gradients in conjunction with the analytic derivatives -// can make "flow noise" effects as presented by Perlin and Neyret. -// -// vec3 {p}s{r}dnoise(vec2 pos {, vec2 per} {, float rot}) -// "pos" is the input (x,y) coordinate -// "per" is the x and y period, where per.x is a positive integer -// and per.y is a positive even integer -// "rot" is the angle to rotate the gradients (any float value, -// where 0.0 is no rotation and 1.0 is one full turn) -// The first component of the 3-element return vector is the noise value. -// The second and third components are the x and y partial derivatives. -// -// float {p}s{r}noise(vec2 pos {, vec2 per} {, float rot}) -// "pos" is the input (x,y) coordinate -// "per" is the x and y period, where per.x is a positive integer -// and per.y is a positive even integer -// "rot" is the angle to rotate the gradients (any float value, -// where 0.0 is no rotation and 1.0 is one full turn) -// The return value is the noise value. -// Partial derivatives are not computed, making these functions faster. -// -// Author: Stefan Gustavson (stefan.gustavson@gmail.com) -// Version 2016-05-10. -// -// Many thanks to Ian McEwan of Ashima Arts for the -// idea of using a permutation polynomial. -// -// Copyright (c) 2016 Stefan Gustavson. All rights reserved. -// Distributed under the MIT license. See LICENSE file. -// https://github.com/stegu/webgl-noise -// - -// Hashed 2-D gradients with an extra rotation. -// (The constant 0.0243902439 is 1/41) -vec2 rgrad2( vec2 p, float rot ) { - - // For more isotropic gradients, sin/cos can be used instead. - float u = permute( permute( p.x ) + p.y ) * 0.0243902439 + rot; // Rotate by shift - u = fract( u ) * 6.28318530718; // 2*pi - return vec2( cos( u ), sin( u )); - -} - -// -// 2-D tiling simplex noise with rotating gradients and analytical derivative. -// The first component of the 3-element return vector is the noise value, -// and the second and third components are the x and y partial derivatives. -// -vec3 psrdnoise(vec2 pos, vec2 per, float rot) { - // Hack: offset y slightly to hide some rare artifacts - pos.y += 0.01; - // Skew to hexagonal grid - vec2 uv = vec2(pos.x + pos.y*0.5, pos.y); - - vec2 i0 = floor(uv); - vec2 f0 = fract(uv); - // Traversal order - vec2 i1 = (f0.x > f0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - - // Unskewed grid points in (x,y) space - vec2 p0 = vec2(i0.x - i0.y * 0.5, i0.y); - vec2 p1 = vec2(p0.x + i1.x - i1.y * 0.5, p0.y + i1.y); - vec2 p2 = vec2(p0.x + 0.5, p0.y + 1.0); - - // Integer grid point indices in (u,v) space - i1 = i0 + i1; - vec2 i2 = i0 + vec2(1.0, 1.0); - - // Vectors in unskewed (x,y) coordinates from - // each of the simplex corners to the evaluation point - vec2 d0 = pos - p0; - vec2 d1 = pos - p1; - vec2 d2 = pos - p2; - - // Wrap i0, i1 and i2 to the desired period before gradient hashing: - // wrap points in (x,y), map to (u,v) - vec3 xw = mod(vec3(p0.x, p1.x, p2.x), per.x); - vec3 yw = mod(vec3(p0.y, p1.y, p2.y), per.y); - vec3 iuw = xw + 0.5 * yw; - vec3 ivw = yw; - - // Create gradients from indices - vec2 g0 = rgrad2(vec2(iuw.x, ivw.x), rot); - vec2 g1 = rgrad2(vec2(iuw.y, ivw.y), rot); - vec2 g2 = rgrad2(vec2(iuw.z, ivw.z), rot); - - // Gradients dot vectors to corresponding corners - // (The derivatives of this are simply the gradients) - vec3 w = vec3(dot(g0, d0), dot(g1, d1), dot(g2, d2)); - - // Radial weights from corners - // 0.8 is the square of 2/sqrt(5), the distance from - // a grid point to the nearest simplex boundary - vec3 t = 0.8 - vec3(dot(d0, d0), dot(d1, d1), dot(d2, d2)); - - // Partial derivatives for analytical gradient computation - vec3 dtdx = -2.0 * vec3(d0.x, d1.x, d2.x); - vec3 dtdy = -2.0 * vec3(d0.y, d1.y, d2.y); - - // Set influence of each surflet to zero outside radius sqrt(0.8) - if (t.x < 0.0) { - dtdx.x = 0.0; - dtdy.x = 0.0; - t.x = 0.0; - } - if (t.y < 0.0) { - dtdx.y = 0.0; - dtdy.y = 0.0; - t.y = 0.0; - } - if (t.z < 0.0) { - dtdx.z = 0.0; - dtdy.z = 0.0; - t.z = 0.0; - } - - // Fourth power of t (and third power for derivative) - vec3 t2 = t * t; - vec3 t4 = t2 * t2; - vec3 t3 = t2 * t; - - // Final noise value is: - // sum of ((radial weights) times (gradient dot vector from corner)) - float n = dot(t4, w); - - // Final analytical derivative (gradient of a sum of scalar products) - vec2 dt0 = vec2(dtdx.x, dtdy.x) * 4.0 * t3.x; - vec2 dn0 = t4.x * g0 + dt0 * w.x; - vec2 dt1 = vec2(dtdx.y, dtdy.y) * 4.0 * t3.y; - vec2 dn1 = t4.y * g1 + dt1 * w.y; - vec2 dt2 = vec2(dtdx.z, dtdy.z) * 4.0 * t3.z; - vec2 dn2 = t4.z * g2 + dt2 * w.z; - - return 11.0*vec3(n, dn0 + dn1 + dn2); -} - -// -// 2-D tiling simplex noise with fixed gradients -// and analytical derivative. -// This function is implemented as a wrapper to "psrdnoise", -// at the minimal cost of three extra additions. -// -vec3 psdnoise(vec2 pos, vec2 per) { - return psrdnoise(pos, per, 0.0); -} - -// -// 2-D tiling simplex noise with rotating gradients, -// but without the analytical derivative. -// -float psrnoise(vec2 pos, vec2 per, float rot) { - // Offset y slightly to hide some rare artifacts - pos.y += 0.001; - // Skew to hexagonal grid - vec2 uv = vec2(pos.x + pos.y*0.5, pos.y); - - vec2 i0 = floor(uv); - vec2 f0 = fract(uv); - // Traversal order - vec2 i1 = (f0.x > f0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - - // Unskewed grid points in (x,y) space - vec2 p0 = vec2(i0.x - i0.y * 0.5, i0.y); - vec2 p1 = vec2(p0.x + i1.x - i1.y * 0.5, p0.y + i1.y); - vec2 p2 = vec2(p0.x + 0.5, p0.y + 1.0); - - // Integer grid point indices in (u,v) space - i1 = i0 + i1; - vec2 i2 = i0 + vec2(1.0, 1.0); - - // Vectors in unskewed (x,y) coordinates from - // each of the simplex corners to the evaluation point - vec2 d0 = pos - p0; - vec2 d1 = pos - p1; - vec2 d2 = pos - p2; - - // Wrap i0, i1 and i2 to the desired period before gradient hashing: - // wrap points in (x,y), map to (u,v) - vec3 xw = mod(vec3(p0.x, p1.x, p2.x), per.x); - vec3 yw = mod(vec3(p0.y, p1.y, p2.y), per.y); - vec3 iuw = xw + 0.5 * yw; - vec3 ivw = yw; - - // Create gradients from indices - vec2 g0 = rgrad2(vec2(iuw.x, ivw.x), rot); - vec2 g1 = rgrad2(vec2(iuw.y, ivw.y), rot); - vec2 g2 = rgrad2(vec2(iuw.z, ivw.z), rot); - - // Gradients dot vectors to corresponding corners - // (The derivatives of this are simply the gradients) - vec3 w = vec3(dot(g0, d0), dot(g1, d1), dot(g2, d2)); - - // Radial weights from corners - // 0.8 is the square of 2/sqrt(5), the distance from - // a grid point to the nearest simplex boundary - vec3 t = 0.8 - vec3(dot(d0, d0), dot(d1, d1), dot(d2, d2)); - - // Set influence of each surflet to zero outside radius sqrt(0.8) - t = max(t, 0.0); - - // Fourth power of t - vec3 t2 = t * t; - vec3 t4 = t2 * t2; - - // Final noise value is: - // sum of ((radial weights) times (gradient dot vector from corner)) - float n = dot(t4, w); - - // Rescale to cover the range [-1,1] reasonably well - return 11.0*n; -} - -// -// 2-D tiling simplex noise with fixed gradients, -// without the analytical derivative. -// This function is implemented as a wrapper to "psrnoise", -// at the minimal cost of three extra additions. -// -float psnoise(vec2 pos, vec2 per) { - return psrnoise(pos, per, 0.0); -} - -// -// 2-D non-tiling simplex noise with rotating gradients and analytical derivative. -// The first component of the 3-element return vector is the noise value, -// and the second and third components are the x and y partial derivatives. -// -vec3 srdnoise(vec2 pos, float rot) { - // Offset y slightly to hide some rare artifacts - pos.y += 0.001; - // Skew to hexagonal grid - vec2 uv = vec2(pos.x + pos.y*0.5, pos.y); - - vec2 i0 = floor(uv); - vec2 f0 = fract(uv); - // Traversal order - vec2 i1 = (f0.x > f0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - - // Unskewed grid points in (x,y) space - vec2 p0 = vec2(i0.x - i0.y * 0.5, i0.y); - vec2 p1 = vec2(p0.x + i1.x - i1.y * 0.5, p0.y + i1.y); - vec2 p2 = vec2(p0.x + 0.5, p0.y + 1.0); - - // Integer grid point indices in (u,v) space - i1 = i0 + i1; - vec2 i2 = i0 + vec2(1.0, 1.0); - - // Vectors in unskewed (x,y) coordinates from - // each of the simplex corners to the evaluation point - vec2 d0 = pos - p0; - vec2 d1 = pos - p1; - vec2 d2 = pos - p2; - - vec3 x = vec3(p0.x, p1.x, p2.x); - vec3 y = vec3(p0.y, p1.y, p2.y); - vec3 iuw = x + 0.5 * y; - vec3 ivw = y; - - // Avoid precision issues in permutation - iuw = mod289(iuw); - ivw = mod289(ivw); - - // Create gradients from indices - vec2 g0 = rgrad2(vec2(iuw.x, ivw.x), rot); - vec2 g1 = rgrad2(vec2(iuw.y, ivw.y), rot); - vec2 g2 = rgrad2(vec2(iuw.z, ivw.z), rot); - - // Gradients dot vectors to corresponding corners - // (The derivatives of this are simply the gradients) - vec3 w = vec3(dot(g0, d0), dot(g1, d1), dot(g2, d2)); - - // Radial weights from corners - // 0.8 is the square of 2/sqrt(5), the distance from - // a grid point to the nearest simplex boundary - vec3 t = 0.8 - vec3(dot(d0, d0), dot(d1, d1), dot(d2, d2)); - - // Partial derivatives for analytical gradient computation - vec3 dtdx = -2.0 * vec3(d0.x, d1.x, d2.x); - vec3 dtdy = -2.0 * vec3(d0.y, d1.y, d2.y); - - // Set influence of each surflet to zero outside radius sqrt(0.8) - if (t.x < 0.0) { - dtdx.x = 0.0; - dtdy.x = 0.0; - t.x = 0.0; - } - if (t.y < 0.0) { - dtdx.y = 0.0; - dtdy.y = 0.0; - t.y = 0.0; - } - if (t.z < 0.0) { - dtdx.z = 0.0; - dtdy.z = 0.0; - t.z = 0.0; - } - - // Fourth power of t (and third power for derivative) - vec3 t2 = t * t; - vec3 t4 = t2 * t2; - vec3 t3 = t2 * t; - - // Final noise value is: - // sum of ((radial weights) times (gradient dot vector from corner)) - float n = dot(t4, w); - - // Final analytical derivative (gradient of a sum of scalar products) - vec2 dt0 = vec2(dtdx.x, dtdy.x) * 4.0 * t3.x; - vec2 dn0 = t4.x * g0 + dt0 * w.x; - vec2 dt1 = vec2(dtdx.y, dtdy.y) * 4.0 * t3.y; - vec2 dn1 = t4.y * g1 + dt1 * w.y; - vec2 dt2 = vec2(dtdx.z, dtdy.z) * 4.0 * t3.z; - vec2 dn2 = t4.z * g2 + dt2 * w.z; - - return 11.0*vec3(n, dn0 + dn1 + dn2); -} - -// -// 2-D non-tiling simplex noise with fixed gradients and analytical derivative. -// This function is implemented as a wrapper to "srdnoise", -// at the minimal cost of three extra additions. -// -vec3 sdnoise(vec2 pos) { - return srdnoise(pos, 0.0); -} - -// -// 2-D non-tiling simplex noise with rotating gradients, -// without the analytical derivative. -// -float srnoise(vec2 pos, float rot) { - // Offset y slightly to hide some rare artifacts - pos.y += 0.001; - // Skew to hexagonal grid - vec2 uv = vec2(pos.x + pos.y*0.5, pos.y); - - vec2 i0 = floor(uv); - vec2 f0 = fract(uv); - // Traversal order - vec2 i1 = (f0.x > f0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - - // Unskewed grid points in (x,y) space - vec2 p0 = vec2(i0.x - i0.y * 0.5, i0.y); - vec2 p1 = vec2(p0.x + i1.x - i1.y * 0.5, p0.y + i1.y); - vec2 p2 = vec2(p0.x + 0.5, p0.y + 1.0); - - // Integer grid point indices in (u,v) space - i1 = i0 + i1; - vec2 i2 = i0 + vec2(1.0, 1.0); - - // Vectors in unskewed (x,y) coordinates from - // each of the simplex corners to the evaluation point - vec2 d0 = pos - p0; - vec2 d1 = pos - p1; - vec2 d2 = pos - p2; - - // Wrap i0, i1 and i2 to the desired period before gradient hashing: - // wrap points in (x,y), map to (u,v) - vec3 x = vec3(p0.x, p1.x, p2.x); - vec3 y = vec3(p0.y, p1.y, p2.y); - vec3 iuw = x + 0.5 * y; - vec3 ivw = y; - - // Avoid precision issues in permutation - iuw = mod289(iuw); - ivw = mod289(ivw); - - // Create gradients from indices - vec2 g0 = rgrad2(vec2(iuw.x, ivw.x), rot); - vec2 g1 = rgrad2(vec2(iuw.y, ivw.y), rot); - vec2 g2 = rgrad2(vec2(iuw.z, ivw.z), rot); - - // Gradients dot vectors to corresponding corners - // (The derivatives of this are simply the gradients) - vec3 w = vec3(dot(g0, d0), dot(g1, d1), dot(g2, d2)); - - // Radial weights from corners - // 0.8 is the square of 2/sqrt(5), the distance from - // a grid point to the nearest simplex boundary - vec3 t = 0.8 - vec3(dot(d0, d0), dot(d1, d1), dot(d2, d2)); - - // Set influence of each surflet to zero outside radius sqrt(0.8) - t = max(t, 0.0); - - // Fourth power of t - vec3 t2 = t * t; - vec3 t4 = t2 * t2; - - // Final noise value is: - // sum of ((radial weights) times (gradient dot vector from corner)) - float n = dot(t4, w); - - // Rescale to cover the range [-1,1] reasonably well - return 11.0*n; -} - -// -// 2-D non-tiling simplex noise with fixed gradients, -// without the analytical derivative. -// This function is implemented as a wrapper to "srnoise", -// at the minimal cost of three extra additions. -// Note: if this kind of noise is all you want, there are faster -// GLSL implementations of non-tiling simplex noise out there. -// This one is included mainly for completeness and compatibility -// with the other functions in the file. -// -float snoise(vec2 pos) { - return srnoise(pos, 0.0); -} diff --git a/packages/core/src/shaderlib/noise_simplex.glsl b/packages/core/src/shaderlib/noise_simplex.glsl deleted file mode 100644 index 0273d3c274..0000000000 --- a/packages/core/src/shaderlib/noise_simplex.glsl +++ /dev/null @@ -1,4 +0,0 @@ -#include -#include -#include -#include diff --git a/packages/core/src/shaderlib/noise_simplex_2D.glsl b/packages/core/src/shaderlib/noise_simplex_2D.glsl deleted file mode 100644 index 811d1859dd..0000000000 --- a/packages/core/src/shaderlib/noise_simplex_2D.glsl +++ /dev/null @@ -1,60 +0,0 @@ -// -// Description : Array and textureless GLSL 2D simplex noise function. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : stegu -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// https://github.com/stegu/webgl-noise -// - -float simplex( vec2 v ) { - - const vec4 C = vec4( 0.211324865405187, // (3.0-sqrt(3.0))/6.0 - 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) - -0.577350269189626, // -1.0 + 2.0 * C.x - 0.024390243902439 ); // 1.0 / 41.0 - // First corner - vec2 i = floor( v + dot( v, C.yy ) ); - vec2 x0 = v - i + dot( i, C.xx ); - - // Other corners - vec2 i1; - //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 - //i1.y = 1.0 - i1.x; - i1 = ( x0.x > x0.y ) ? vec2( 1.0, 0.0 ) : vec2( 0.0, 1.0 ); - // x0 = x0 - 0.0 + 0.0 * C.xx ; - // x1 = x0 - i1 + 1.0 * C.xx ; - // x2 = x0 - 1.0 + 2.0 * C.xx ; - vec4 x12 = x0.xyxy + C.xxzz; - x12.xy -= i1; - - // Permutations - i = mod289( i ); // Avoid truncation effects in permutation - vec3 p = permute( permute( i.y + vec3( 0.0, i1.y, 1.0 ) ) - + i.x + vec3( 0.0, i1.x, 1.0 ) ); - - vec3 m = max( 0.5 - vec3( dot( x0, x0 ), dot( x12.xy, x12.xy ), dot( x12.zw, x12.zw ) ), 0.0 ); - m = m*m ; - m = m*m ; - - // Gradients: 41 points uniformly over a line, mapped onto a diamond. - // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) - - vec3 x = 2.0 * fract( p * C.www ) - 1.0; - vec3 h = abs( x ) - 0.5; - vec3 ox = floor( x + 0.5 ); - vec3 a0 = x - ox; - - // Normalise gradients implicitly by scaling m - // Approximation of: m *= inversesqrt( a0*a0 + h*h ); - m *= 1.79284291400159 - 0.85373472095314 * ( a0 * a0 + h * h ); - - // Compute final noise value at P - vec3 g; - g.x = a0.x * x0.x + h.x * x0.y; - g.yz = a0.yz * x12.xz + h.yz * x12.yw; - return 130.0 * dot( m, g ); - -} diff --git a/packages/core/src/shaderlib/noise_simplex_3D.glsl b/packages/core/src/shaderlib/noise_simplex_3D.glsl deleted file mode 100644 index c9ec149613..0000000000 --- a/packages/core/src/shaderlib/noise_simplex_3D.glsl +++ /dev/null @@ -1,81 +0,0 @@ -// -// Description : Array and textureless GLSL 2D/3D/4D simplex -// noise functions. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : stegu -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// https://github.com/stegu/webgl-noise -// - -float simplex( vec3 v ) { - - const vec2 C = vec2( 1.0 / 6.0, 1.0 / 3.0 ); - const vec4 D = vec4( 0.0, 0.5, 1.0, 2.0 ); - - // First corner - vec3 i = floor( v + dot( v, C.yyy ) ); - vec3 x0 = v - i + dot( i, C.xxx ); - - // Other corners - vec3 g = step( x0.yzx, x0.xyz ); - vec3 l = 1.0 - g; - vec3 i1 = min( g.xyz, l.zxy ); - vec3 i2 = max( g.xyz, l.zxy ); - - vec3 x1 = x0 - i1 + C.xxx; - vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y - vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y - - // Permutations - i = mod289( i ); - vec4 p = permute( permute( permute( - i.z + vec4(0.0, i1.z, i2.z, 1.0 )) - + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) - + i.x + vec4(0.0, i1.x, i2.x, 1.0 )); - - // Gradients: 7x7 points over a square, mapped onto an octahedron. - // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294) - float n_ = 0.142857142857; // 1.0/7.0 - vec3 ns = n_ * D.wyz - D.xzx; - - vec4 j = p - 49.0 * floor( p * ns.z * ns.z ); // mod(p,7*7) - - vec4 x_ = floor(j * ns.z); - vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N) - - vec4 x = x_ *ns.x + ns.yyyy; - vec4 y = y_ *ns.x + ns.yyyy; - vec4 h = 1.0 - abs( x ) - abs( y ); - - vec4 b0 = vec4( x.xy, y.xy ); - vec4 b1 = vec4( x.zw, y.zw ); - - vec4 s0 = floor( b0 ) * 2.0 + 1.0; - vec4 s1 = floor( b1 ) * 2.0 + 1.0; - vec4 sh = - step( h, vec4( 0.0 ) ); - - vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy ; - vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww ; - - vec3 p0 = vec3( a0.xy, h.x ); - vec3 p1 = vec3( a0.zw, h.y ); - vec3 p2 = vec3( a1.xy, h.z ); - vec3 p3 = vec3( a1.zw, h.w ); - - //Normalise gradients - vec4 norm = taylorInvSqrt( vec4( dot( p0, p0 ), dot( p1, p1 ), dot( p2, p2 ), dot( p3, p3 ) ) ); - p0 *= norm.x; - p1 *= norm.y; - p2 *= norm.z; - p3 *= norm.w; - - // Mix final noise value - vec4 m = max( 0.6 - vec4( dot( x0, x0 ), dot( x1, x1 ), dot( x2, x2 ), dot( x3, x3 ) ), 0.0 ); - m = m * m; - return 42.0 * dot( m*m, vec4( dot( p0, x0 ), dot( p1, x1 ), - dot( p2, x2 ), dot( p3, x3 ) ) ); - -} diff --git a/packages/core/src/shaderlib/noise_simplex_4D.glsl b/packages/core/src/shaderlib/noise_simplex_4D.glsl deleted file mode 100644 index eec6c09d5d..0000000000 --- a/packages/core/src/shaderlib/noise_simplex_4D.glsl +++ /dev/null @@ -1,98 +0,0 @@ -// -// Description : Array and textureless GLSL 2D/3D/4D simplex -// noise functions. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : stegu -// Lastmod : 20110822 (ijm) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// https://github.com/stegu/webgl-noise -// - -vec4 grad4( float j, vec4 ip ) { - - const vec4 ones = vec4( 1.0, 1.0, 1.0, -1.0 ); - vec4 p, s; - - p.xyz = floor( fract( vec3( j ) * ip.xyz ) * 7.0 ) * ip.z - 1.0; - p.w = 1.5 - dot( abs( p.xyz ), ones.xyz ); - s = vec4( lessThan( p, vec4( 0.0 ) ) ); - p.xyz = p.xyz + ( s.xyz * 2.0 - 1.0 ) * s.www; - - return p; - -} - -// (sqrt(5) - 1)/4 = F4, used once below -#define F4 0.309016994374947451 - -float simplex(vec4 v) { - - const vec4 C = vec4( 0.138196601125011, // (5 - sqrt(5))/20 G4 - 0.276393202250021, // 2 * G4 - 0.414589803375032, // 3 * G4 - -0.447213595499958); // -1 + 4 * G4 - - // First corner - vec4 i = floor( v + dot( v, vec4( F4 ) ) ); - vec4 x0 = v - i + dot( i, C.xxxx ); - - // Other corners - - // Rank sorting originally contributed by Bill Licea-Kane, AMD (formerly ATI) - vec4 i0; - vec3 isX = step( x0.yzw, x0.xxx ); - vec3 isYZ = step( x0.zww, x0.yyz ); - i0.x = isX.x + isX.y + isX.z; - i0.yzw = 1.0 - isX; - i0.y += isYZ.x + isYZ.y; - i0.zw += 1.0 - isYZ.xy; - i0.z += isYZ.z; - i0.w += 1.0 - isYZ.z; - - vec4 i3 = clamp( i0, 0.0, 1.0 ); - vec4 i2 = clamp( i0 - 1.0, 0.0, 1.0 ); - vec4 i1 = clamp( i0 - 2.0, 0.0, 1.0 ); - - vec4 x1 = x0 - i1 + C.xxxx; - vec4 x2 = x0 - i2 + C.yyyy; - vec4 x3 = x0 - i3 + C.zzzz; - vec4 x4 = x0 + C.wwww; - - // Permutations - i = mod289( i ); - float j0 = permute( permute( permute( permute( i.w ) + i.z ) + i.y ) + i.x ); - vec4 j1 = permute( permute( permute( permute ( - i.w + vec4(i1.w, i2.w, i3.w, 1.0 )) - + i.z + vec4(i1.z, i2.z, i3.z, 1.0 )) - + i.y + vec4(i1.y, i2.y, i3.y, 1.0 )) - + i.x + vec4(i1.x, i2.x, i3.x, 1.0 )); - - // Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope - // 7*7*6 = 294, which is close to the ring size 17*17 = 289. - vec4 ip = vec4( 1.0 / 294.0, 1.0 / 49.0, 1.0 / 7.0, 0.0 ); - - vec4 p0 = grad4(j0, ip); - vec4 p1 = grad4(j1.x, ip); - vec4 p2 = grad4(j1.y, ip); - vec4 p3 = grad4(j1.z, ip); - vec4 p4 = grad4(j1.w, ip); - - // Normalise gradients - vec4 norm = taylorInvSqrt( vec4( dot( p0, p0 ), dot( p1, p1 ), dot( p2, p2 ), dot( p3, p3 ) ) ); - p0 *= norm.x; - p1 *= norm.y; - p2 *= norm.z; - p3 *= norm.w; - p4 *= taylorInvSqrt( dot( p4, p4 ) ); - - // Mix contributions from the five corners - vec3 m0 = max( 0.6 - vec3( dot( x0, x0 ), dot( x1, x1 ), dot( x2, x2 ) ), 0.0 ); - vec2 m1 = max( 0.6 - vec2( dot( x3, x3 ), dot( x4, x4 ) ), 0.0 ); - m0 = m0 * m0; - m1 = m1 * m1; - return 49.0 * ( dot(m0*m0, vec3( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 ))) - + dot(m1*m1, vec2( dot( p3, x3 ), dot( p4, x4 ) ) ) ) ; - -} diff --git a/packages/core/src/shaderlib/normal_get.glsl b/packages/core/src/shaderlib/normal_get.glsl deleted file mode 100644 index f92b98e7ab..0000000000 --- a/packages/core/src/shaderlib/normal_get.glsl +++ /dev/null @@ -1,60 +0,0 @@ -// gl_FrontFacing has random value on Adreno GPUs -// the Adreno bug is only when gl_FrontFacing is inside a function -// https://bugs.chromium.org/p/chromium/issues/detail?id=1154842 -vec3 getNormal(bool isFrontFacing){ - #ifdef RENDERER_HAS_NORMAL - vec3 normal = normalize(v_normal); - #elif defined(HAS_DERIVATIVES) - vec3 pos_dx = dFdx(v_pos); - vec3 pos_dy = dFdy(v_pos); - vec3 normal = normalize( cross(pos_dx, pos_dy) ); - normal *= camera_ProjectionParams.x; - #else - vec3 normal = vec3(0, 0, 1); - #endif - - normal *= float( isFrontFacing ) * 2.0 - 1.0; - return normal; -} - -vec3 getNormalByNormalTexture(mat3 tbn, sampler2D normalTexture, float normalIntensity, vec2 uv, bool isFrontFacing){ - vec3 normal = texture2D(normalTexture, uv).rgb; - normal = normalize(tbn * ((2.0 * normal - 1.0) * vec3(normalIntensity, normalIntensity, 1.0))); - normal *= float( isFrontFacing ) * 2.0 - 1.0; - - return normal; -} - -mat3 getTBN(bool isFrontFacing){ - #if defined(RENDERER_HAS_NORMAL) && defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) ) - mat3 tbn = v_TBN; - #else - vec3 normal = getNormal(isFrontFacing); - vec3 position = v_pos; - vec2 uv = isFrontFacing? v_uv: -v_uv; - - #ifdef HAS_DERIVATIVES - // ref: http://www.thetenthplanet.de/archives/1180 - // get edge vectors of the pixel triangle - vec3 dp1 = dFdx(position); - vec3 dp2 = dFdy(position); - vec2 duv1 = dFdx(uv); - vec2 duv2 = dFdy(uv); - - // solve the linear system - vec3 dp2perp = cross(dp2, normal); - vec3 dp1perp = cross(normal, dp1); - vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x; - vec3 bitangent = dp2perp * duv1.y + dp1perp * duv2.y; - - // construct a scale-invariant frame - float denom = max( dot(tangent, tangent), dot(bitangent, bitangent) ); - float invmax = (denom == 0.0) ? 0.0 : camera_ProjectionParams.x / sqrt( denom ); - mat3 tbn = mat3(tangent * invmax, bitangent * invmax, normal); - #else - mat3 tbn = mat3(vec3(0.0), vec3(0.0), normal); - #endif - #endif - - return tbn; -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/normal_share.glsl b/packages/core/src/shaderlib/normal_share.glsl deleted file mode 100644 index c22f058f29..0000000000 --- a/packages/core/src/shaderlib/normal_share.glsl +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef MATERIAL_OMIT_NORMAL - #ifdef RENDERER_HAS_NORMAL - varying vec3 v_normal; - #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) ) - varying mat3 v_TBN; - #endif - #endif -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/normal_vert.glsl b/packages/core/src/shaderlib/normal_vert.glsl deleted file mode 100644 index 096a4595d1..0000000000 --- a/packages/core/src/shaderlib/normal_vert.glsl +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef MATERIAL_OMIT_NORMAL - #ifdef RENDERER_HAS_NORMAL - v_normal = normalize( mat3(renderer_NormalMat) * normal ); - - #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) ) - vec3 tangentW = normalize( mat3(renderer_NormalMat) * tangent.xyz ); - vec3 bitangentW = cross( v_normal, tangentW ) * tangent.w; - - v_TBN = mat3( tangentW, bitangentW, v_normal ); - #endif - #endif -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/particle/index.ts b/packages/core/src/shaderlib/particle/index.ts deleted file mode 100644 index 83893232ef..0000000000 --- a/packages/core/src/shaderlib/particle/index.ts +++ /dev/null @@ -1,33 +0,0 @@ -import particle_common from "./particle_common.glsl"; -import velocity_over_lifetime_module from "./velocity_over_lifetime_module.glsl"; -import rotation_over_lifetime_module from "./rotation_over_lifetime_module.glsl"; -import size_over_lifetime_module from "./size_over_lifetime_module.glsl"; -import color_over_lifetime_module from "./color_over_lifetime_module.glsl"; -import texture_sheet_animation_module from "./texture_sheet_animation_module.glsl"; -import force_over_lifetime_module from "./force_over_lifetime_module.glsl"; -import limit_velocity_over_lifetime_module from "./limit_velocity_over_lifetime_module.glsl"; -import particle_feedback_simulation from "./particle_feedback_simulation.glsl"; - -import sphere_billboard from "./sphere_billboard.glsl"; -import stretched_billboard from "./stretched_billboard.glsl"; -import vertical_billboard from "./vertical_billboard.glsl"; -import horizontal_billboard from "./horizontal_billboard.glsl"; -import particle_mesh from "./particle_mesh.glsl"; - -export default { - particle_common, - velocity_over_lifetime_module, - rotation_over_lifetime_module, - size_over_lifetime_module, - color_over_lifetime_module, - texture_sheet_animation_module, - force_over_lifetime_module, - limit_velocity_over_lifetime_module, - particle_feedback_simulation, - - sphere_billboard, - stretched_billboard, - vertical_billboard, - horizontal_billboard, - particle_mesh -}; diff --git a/packages/core/src/shaderlib/pbr/brdf.glsl b/packages/core/src/shaderlib/pbr/brdf.glsl deleted file mode 100644 index 11a9bc1f3e..0000000000 --- a/packages/core/src/shaderlib/pbr/brdf.glsl +++ /dev/null @@ -1,254 +0,0 @@ - -#ifdef MATERIAL_ENABLE_SHEEN - uniform sampler2D scene_PrefilteredDFG; -#endif - -float F_Schlick(float f0, float f90, float dotLH) { - return f0 + (f90 - f0) * (pow(1.0 - dotLH, 5.0)); -} - -vec3 F_Schlick(vec3 f0, float f90, float dotLH ) { - - // Original approximation by Christophe Schlick '94 - // float fresnel = pow( 1.0 - dotLH, 5.0 ); - - // Optimized variant (presented by Epic at SIGGRAPH '13) - // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf - float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH ); - - return (f90 - f0 ) * fresnel + f0; - -} - -// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2 -// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf -float G_GGX_SmithCorrelated(float alpha, float dotNL, float dotNV ) { - - float a2 = pow2( alpha ); - - // dotNL and dotNV are explicitly swapped. This is not a mistake. - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - - return 0.5 / max( gv + gl, EPSILON ); - -} - -#ifdef MATERIAL_ENABLE_ANISOTROPY - // Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs" - // Heitz http://jcgt.org/published/0003/02/03/paper.pdf - float G_GGX_SmithCorrelated_Anisotropic(float at, float ab, float ToV, float BoV, float ToL, float BoL, float NoV, float NoL) { - float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV)); - float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL)); - return 0.5 / max(lambdaV + lambdaL, EPSILON); - } -#endif - -// Microfacet Models for Refraction through Rough Surfaces - equation (33) -// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html -// alpha is "roughness squared" in Disney’s reparameterization -float D_GGX(float alpha, float dotNH ) { - - float a2 = pow2( alpha ); - - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1 - - return RECIPROCAL_PI * a2 / pow2( denom ); - -} - -#ifdef MATERIAL_ENABLE_SHEEN - // http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf - float D_Charlie(float roughness, float dotNH) { - float invAlpha = 1.0 / roughness; - float cos2h = dotNH * dotNH; - float sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16 - return (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI); - } - - // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886". - float V_Neubelt(float NoV, float NoL) { - return saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV))); - } - - vec3 sheenBRDF(vec3 incidentDirection, Geometry geometry, vec3 sheenColor, float sheenRoughness) { - vec3 halfDir = normalize(incidentDirection + geometry.viewDir); - float dotNL = saturate(dot(geometry.normal, incidentDirection)); - float dotNH = saturate(dot(geometry.normal, halfDir)); - float D = D_Charlie(sheenRoughness, dotNH); - float V = V_Neubelt(geometry.dotNV, dotNL); - vec3 F = sheenColor; - return D * V * F; - } - - float prefilteredSheenDFG(float dotNV, float sheenRoughness) { - #ifdef HAS_TEX_LOD - return texture2DLodEXT(scene_PrefilteredDFG, vec2(dotNV, sheenRoughness), 0.0).b; - #else - return texture2D(scene_PrefilteredDFG, vec2(dotNV, sheenRoughness),0.0).b; - #endif - } -#endif - -#ifdef MATERIAL_ENABLE_ANISOTROPY - // GGX Distribution Anisotropic - // https://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf Addenda - float D_GGX_Anisotropic(float at, float ab, float ToH, float BoH, float NoH) { - float a2 = at * ab; - vec3 d = vec3(ab * ToH, at * BoH, a2 * NoH); - float d2 = dot(d, d); - float b2 = a2 / d2; - return a2 * b2 * b2 * RECIPROCAL_PI; - } -#endif - -float DG_GGX(float alpha, float dotNV, float dotNL, float dotNH) { - float D = D_GGX( alpha, dotNH ); - float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - return G * D; -} - -#ifdef MATERIAL_ENABLE_ANISOTROPY - float DG_GGX_anisotropic(vec3 h, vec3 l, Geometry geometry, float alpha, float dotNV, float dotNL, float dotNH) { - vec3 t = geometry.anisotropicT; - vec3 b = geometry.anisotropicB; - vec3 v = geometry.viewDir; - - float dotTV = dot(t, v); - float dotBV = dot(b, v); - float dotTL = dot(t, l); - float dotBL = dot(b, l); - float dotTH = dot(t, h); - float dotBH = dot(b, h); - - // Aniso parameter remapping - // https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf page 24 - float at = max(alpha * (1.0 + geometry.anisotropy), MIN_ROUGHNESS); - float ab = max(alpha * (1.0 - geometry.anisotropy), MIN_ROUGHNESS); - - // specular anisotropic BRDF - float D = D_GGX_Anisotropic(at, ab, dotTH, dotBH, dotNH); - float G = G_GGX_SmithCorrelated_Anisotropic(at, ab, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL); - - return G * D; - } -#endif - -#ifdef MATERIAL_ENABLE_IRIDESCENCE - vec3 iorToFresnel0(vec3 transmittedIOR, float incidentIOR) { - return pow((transmittedIOR - incidentIOR) / (transmittedIOR + incidentIOR),vec3(2.0)); - } - - float iorToFresnel0(float transmittedIOR, float incidentIOR) { - return pow((transmittedIOR - incidentIOR) / (transmittedIOR + incidentIOR),2.0); - } - - // Assume air interface for top - // Note: We don't handle the case fresnel0 == 1 - vec3 fresnelToIOR(vec3 f0){ - vec3 sqrtF0 = sqrt(f0); - return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); - } - - // Fresnel equations for dielectric/dielectric interfaces. - // Ref: https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html - // Evaluation XYZ sensitivity curves in Fourier space - vec3 evalSensitivity(float opd, vec3 shift){ - // Use Gaussian fits, given by 3 parameters: val, pos and var - float phase = 2.0 * PI * opd * 1.0e-9; - const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); - const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); - const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); - vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-var * pow2(phase)); - xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow2(phase)); - xyz /= 1.0685e-7; - // XYZ to RGB color space - const mat3 XYZ_TO_RGB = mat3( 3.2404542, -0.9692660, 0.0556434, - -1.5371385, 1.8760108, -0.2040259, - -0.4985314, 0.0415560, 1.0572252); - vec3 rgb = XYZ_TO_RGB * xyz; - return rgb; - } - - vec3 evalIridescenceSpecular(float outsideIOR, float dotNV, float thinIOR, vec3 baseF0, float baseF90, float iridescenceThickness){ - vec3 iridescence = vec3(1.0); - // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0 - float iridescenceIOR = mix( outsideIOR, thinIOR, smoothstep( 0.0, 0.03, iridescenceThickness ) ); - // Evaluate the cosTheta on the base layer (Snell law) - float sinTheta2Sq = pow( outsideIOR / iridescenceIOR, 2.0) * (1.0 - pow( dotNV, 2.0)); - float cosTheta2Sq = 1.0 - sinTheta2Sq; - // Handle total internal reflection - if (cosTheta2Sq < 0.0) { - return iridescence; - } - float cosTheta2 = sqrt(cosTheta2Sq); - - // First interface - float f0 = iorToFresnel0(iridescenceIOR, outsideIOR); - float reflectance = F_Schlick(f0, baseF90, dotNV); - float t121 = 1.0 - reflectance; - float phi12 = 0.0; - // iridescenceIOR has limited greater than 1.0 - // if (iridescenceIOR < outsideIOR) {phi12 = PI;} - float phi21 = PI - phi12; - - // Second interface - vec3 baseIOR = fresnelToIOR(clamp(baseF0, 0.0, 0.9999)); // guard against 1.0 - vec3 r1 = iorToFresnel0(baseIOR, iridescenceIOR); - vec3 r23 = F_Schlick(r1, baseF90, cosTheta2); - vec3 phi23 =vec3(0.0); - if (baseIOR[0] < iridescenceIOR) {phi23[0] = PI;} - if (baseIOR[1] < iridescenceIOR) {phi23[1] = PI;} - if (baseIOR[2] < iridescenceIOR) {phi23[2] = PI;} - - // Phase shift - float opd = 2.0 * iridescenceIOR * iridescenceThickness * cosTheta2; - vec3 phi = vec3(phi21) + phi23; - - // Compound terms - vec3 r123 = clamp(reflectance * r23, 1e-5, 0.9999); - vec3 sr123 = sqrt(r123); - vec3 rs = pow2(t121) * r23 / (vec3(1.0) - r123); - // Reflectance term for m = 0 (DC term amplitude) - vec3 c0 = reflectance + rs; - iridescence = c0; - // Reflectance term for m > 0 (pairs of diracs) - vec3 cm = rs - t121; - for (int m = 1; m <= 2; ++m) { - cm *= sr123; - vec3 sm = 2.0 * evalSensitivity(float(m) * opd, float(m) * phi); - iridescence += cm * sm; - } - return iridescence = max(iridescence, vec3(0.0)); - } -#endif - -// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility -vec3 BRDF_Specular_GGX(vec3 incidentDirection, Geometry geometry, Material material, vec3 normal, vec3 specularColor, float roughness ) { - - float alpha = pow2( roughness ); // UE4's roughness - - vec3 halfDir = normalize( incidentDirection + geometry.viewDir ); - - float dotNL = saturate( dot( normal, incidentDirection ) ); - float dotNV = saturate( dot( normal, geometry.viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotLH = saturate( dot( incidentDirection, halfDir ) ); - - vec3 F = F_Schlick( specularColor, material.specularF90, dotLH ); - #ifdef MATERIAL_ENABLE_IRIDESCENCE - F = mix(F, material.iridescenceSpecularColor, material.iridescenceFactor); - #endif - - #ifdef MATERIAL_ENABLE_ANISOTROPY - float GD = DG_GGX_anisotropic(halfDir, incidentDirection, geometry, alpha, dotNV, dotNL, dotNH); - #else - float GD = DG_GGX(alpha, dotNV, dotNL, dotNH); - #endif - - return F * GD; -} - -vec3 BRDF_Diffuse_Lambert(vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} diff --git a/packages/core/src/shaderlib/pbr/btdf.glsl b/packages/core/src/shaderlib/pbr/btdf.glsl deleted file mode 100644 index c526072195..0000000000 --- a/packages/core/src/shaderlib/pbr/btdf.glsl +++ /dev/null @@ -1,37 +0,0 @@ -#include - -#ifdef MATERIAL_ENABLE_TRANSMISSION - uniform sampler2D camera_OpaqueTexture; - vec3 evaluateTransmission(Geometry geometry, Material material) { - RefractionModelResult ray; - #if REFRACTION_MODE == 0 - // RefractionMode.Sphere - refractionModelSphere(-geometry.viewDir, geometry.position, geometry.normal, material.IOR, material.thickness, ray); - #elif REFRACTION_MODE == 1 - // RefractionMode.Planar - refractionModelPlanar(-geometry.viewDir, geometry.position, geometry.normal, material.IOR, material.thickness, ray); - #endif - - vec3 refractedRayExit = ray.positionExit; - - // We calculate the screen space position of the refracted point - vec4 samplingPositionNDC = camera_ProjMat * camera_ViewMat * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = (samplingPositionNDC.xy / samplingPositionNDC.w) * 0.5 + 0.5; - - // Sample the opaque texture to get the transmitted light - vec3 refractionTransmitted = texture2DSRGB(camera_OpaqueTexture, refractionCoords).rgb; - refractionTransmitted *= material.diffuseColor; - - // Use specularFGD as an approximation of the fresnel effect - // https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf - refractionTransmitted *= (1.0 - material.envSpecularDFG); - - #ifdef MATERIAL_HAS_THICKNESS - // Absorption coefficient from Disney: http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf - vec3 transmittance = min(vec3(1.0), exp(-material.absorptionCoefficient * ray.transmissionLength)); - refractionTransmitted *= transmittance; - #endif - - return refractionTransmitted; - } -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/pbr/direct_irradiance_frag_define.glsl b/packages/core/src/shaderlib/pbr/direct_irradiance_frag_define.glsl deleted file mode 100644 index 9ef1c7483d..0000000000 --- a/packages/core/src/shaderlib/pbr/direct_irradiance_frag_define.glsl +++ /dev/null @@ -1,147 +0,0 @@ -#include - -void sheenLobe(Geometry geometry, Material material, vec3 incidentDirection, vec3 attenuationIrradiance, inout vec3 diffuseColor, inout vec3 specularColor){ - #ifdef MATERIAL_ENABLE_SHEEN - diffuseColor *= material.sheenScaling; - specularColor *= material.sheenScaling; - - specularColor += attenuationIrradiance * sheenBRDF(incidentDirection, geometry, material.sheenColor, material.sheenRoughness); - #endif -} - -void addDirectRadiance(vec3 incidentDirection, vec3 color, Geometry geometry, Material material, inout ReflectedLight reflectedLight) { - float attenuation = 1.0; - - #ifdef MATERIAL_ENABLE_CLEAR_COAT - float clearCoatDotNL = saturate( dot( geometry.clearCoatNormal, incidentDirection ) ); - vec3 clearCoatIrradiance = clearCoatDotNL * color; - - reflectedLight.directSpecular += material.clearCoat * clearCoatIrradiance * BRDF_Specular_GGX( incidentDirection, geometry, material, geometry.clearCoatNormal, vec3( 0.04 ), material.clearCoatRoughness ); - attenuation -= material.clearCoat * F_Schlick(0.04, 1.0, geometry.clearCoatDotNV); - #endif - - float dotNL = saturate( dot( geometry.normal, incidentDirection ) ); - vec3 irradiance = dotNL * color * PI; - - reflectedLight.directSpecular += attenuation * irradiance * BRDF_Specular_GGX( incidentDirection, geometry, material, geometry.normal, material.specularF0, material.roughness) * material.energyCompensation; - reflectedLight.directDiffuse += attenuation * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); - - // Sheen Lobe - sheenLobe(geometry, material, incidentDirection, attenuation * irradiance, reflectedLight.directDiffuse, reflectedLight.directSpecular); - -} - -#ifdef SCENE_DIRECT_LIGHT_COUNT - - void addDirectionalDirectLightRadiance(DirectLight directionalLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) { - vec3 color = directionalLight.color; - vec3 direction = -directionalLight.direction; - - addDirectRadiance( direction, color, geometry, material, reflectedLight ); - - } - -#endif - -#ifdef SCENE_POINT_LIGHT_COUNT - - void addPointDirectLightRadiance(PointLight pointLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) { - - vec3 lVector = pointLight.position - geometry.position; - vec3 direction = normalize( lVector ); - - float lightDistance = length( lVector ); - - vec3 color = pointLight.color; - color *= clamp(1.0 - pow(lightDistance/pointLight.distance, 4.0), 0.0, 1.0); - - addDirectRadiance( direction, color, geometry, material, reflectedLight ); - - } - -#endif - -#ifdef SCENE_SPOT_LIGHT_COUNT - - void addSpotDirectLightRadiance(SpotLight spotLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) { - - vec3 lVector = spotLight.position - geometry.position; - vec3 direction = normalize( lVector ); - - float lightDistance = length( lVector ); - float angleCos = dot( direction, -spotLight.direction ); - - float spotEffect = smoothstep( spotLight.penumbraCos, spotLight.angleCos, angleCos ); - float decayEffect = clamp(1.0 - pow(lightDistance/spotLight.distance, 4.0), 0.0, 1.0); - - vec3 color = spotLight.color; - color *= spotEffect * decayEffect; - - addDirectRadiance( direction, color, geometry, material, reflectedLight ); - - } - - -#endif - -void addTotalDirectRadiance(Geometry geometry, Material material, inout ReflectedLight reflectedLight){ - float shadowAttenuation = 1.0; - - #ifdef SCENE_DIRECT_LIGHT_COUNT - shadowAttenuation = 1.0; - #ifdef SCENE_IS_CALCULATE_SHADOWS - shadowAttenuation *= sampleShadowMap(); - #endif - - DirectLight directionalLight; - for ( int i = 0; i < SCENE_DIRECT_LIGHT_COUNT; i ++ ) { - // warning: use `continue` syntax may trigger flickering bug in safri 16.1. - if(!isRendererCulledByLight(renderer_Layer.xy, scene_DirectLightCullingMask[i])){ - directionalLight.color = scene_DirectLightColor[i]; - #ifdef SCENE_IS_CALCULATE_SHADOWS - if (i == 0) { // Sun light index is always 0 - directionalLight.color *= shadowAttenuation; - } - #endif - directionalLight.direction = scene_DirectLightDirection[i]; - addDirectionalDirectLightRadiance( directionalLight, geometry, material, reflectedLight ); - } - } - - #endif - - #ifdef SCENE_POINT_LIGHT_COUNT - - PointLight pointLight; - - for ( int i = 0; i < SCENE_POINT_LIGHT_COUNT; i ++ ) { - if(!isRendererCulledByLight(renderer_Layer.xy, scene_PointLightCullingMask[i])){ - pointLight.color = scene_PointLightColor[i]; - pointLight.position = scene_PointLightPosition[i]; - pointLight.distance = scene_PointLightDistance[i]; - - addPointDirectLightRadiance( pointLight, geometry, material, reflectedLight ); - } - } - - #endif - - #ifdef SCENE_SPOT_LIGHT_COUNT - - SpotLight spotLight; - - for ( int i = 0; i < SCENE_SPOT_LIGHT_COUNT; i ++ ) { - if(!isRendererCulledByLight(renderer_Layer.xy, scene_SpotLightCullingMask[i])){ - spotLight.color = scene_SpotLightColor[i]; - spotLight.position = scene_SpotLightPosition[i]; - spotLight.direction = scene_SpotLightDirection[i]; - spotLight.distance = scene_SpotLightDistance[i]; - spotLight.angleCos = scene_SpotLightAngleCos[i]; - spotLight.penumbraCos = scene_SpotLightPenumbraCos[i]; - - addSpotDirectLightRadiance( spotLight, geometry, material, reflectedLight ); - } - } - - #endif -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/pbr/ibl_frag_define.glsl b/packages/core/src/shaderlib/pbr/ibl_frag_define.glsl deleted file mode 100644 index 9149f30dff..0000000000 --- a/packages/core/src/shaderlib/pbr/ibl_frag_define.glsl +++ /dev/null @@ -1,87 +0,0 @@ -// ------------------------Diffuse------------------------ - -// sh need be pre-scaled in CPU. -vec3 getLightProbeIrradiance(vec3 sh[9], vec3 normal){ - vec3 result = sh[0] + - - sh[1] * (normal.y) + - sh[2] * (normal.z) + - sh[3] * (normal.x) + - - sh[4] * (normal.y * normal.x) + - sh[5] * (normal.y * normal.z) + - sh[6] * (3.0 * normal.z * normal.z - 1.0) + - sh[7] * (normal.z * normal.x) + - sh[8] * (normal.x * normal.x - normal.y * normal.y); - - return max(result, vec3(0.0)); - -} - -// ------------------------Specular------------------------ - -// Returns raw DFG approximation coefficients (split-sum LUT approximation) -vec2 envDFGApprox(float roughness, float dotNV) { - const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); - const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); - vec4 r = roughness * c0 + c1; - float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; - return vec2( -1.04, 1.04 ) * a004 + r.zw; -} - -// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile -vec3 envBRDFApprox(vec3 f0, float f90, float roughness, float dotNV ) { - vec2 AB = envDFGApprox(roughness, dotNV); - return f0 * AB.x + f90 * AB.y; -} - - -float getSpecularMIPLevel(float roughness, int maxMIPLevel ) { - return roughness * float(maxMIPLevel); -} - -vec3 getReflectedVector(Geometry geometry, vec3 n) { - #ifdef MATERIAL_ENABLE_ANISOTROPY - vec3 r = reflect(-geometry.viewDir, geometry.anisotropicN); - #else - vec3 r = reflect(-geometry.viewDir, n); - #endif - - return r; -} - -vec3 getLightProbeRadiance(Geometry geometry, vec3 normal, float roughness, int maxMIPLevel, float specularIntensity) { - - #ifndef SCENE_USE_SPECULAR_ENV - return vec3(0); - #else - vec3 reflectVec = getReflectedVector(geometry, normal); - - float specularMIPLevel = getSpecularMIPLevel(roughness, maxMIPLevel ); - - #ifdef HAS_TEX_LOD - vec4 envMapColor = textureCubeLodEXT( scene_EnvSpecularSampler, reflectVec, specularMIPLevel ); - #else - vec4 envMapColor = textureCube( scene_EnvSpecularSampler, reflectVec, specularMIPLevel ); - #endif - - #ifdef ENGINE_NO_SRGB - envMapColor = sRGBToLinear(envMapColor); - #endif - - return envMapColor.rgb * specularIntensity; - - #endif - -} - - -void evaluateSheenIBL(Geometry geometry, Material material, float radianceAttenuation, inout vec3 diffuseColor, inout vec3 specularColor){ - #ifdef MATERIAL_ENABLE_SHEEN - diffuseColor *= material.sheenScaling; - specularColor *= material.sheenScaling; - - vec3 reflectance = material.specularAO * radianceAttenuation * material.approxIBLSheenDG * material.sheenColor; - specularColor += reflectance; - #endif -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/pbr/index.ts b/packages/core/src/shaderlib/pbr/index.ts deleted file mode 100644 index c2cfb9210f..0000000000 --- a/packages/core/src/shaderlib/pbr/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -import pbr_frag_define from "./pbr_frag_define.glsl"; - -/** direct + IBL */ -import pbr_helper from "./pbr_helper.glsl"; -import brdf from "./brdf.glsl"; -import direct_irradiance_frag_define from "./direct_irradiance_frag_define.glsl"; -import ibl_frag_define from "./ibl_frag_define.glsl"; - -import pbr_frag from "./pbr_frag.glsl"; - -import btdf from "./btdf.glsl"; -import refraction from "./refraction.glsl"; - -export default { - pbr_frag_define, - - pbr_helper, - brdf, - direct_irradiance_frag_define, - ibl_frag_define, - - pbr_frag, - - btdf, - refraction -}; diff --git a/packages/core/src/shaderlib/pbr/pbr_frag.glsl b/packages/core/src/shaderlib/pbr/pbr_frag.glsl deleted file mode 100644 index bb1ae0a674..0000000000 --- a/packages/core/src/shaderlib/pbr/pbr_frag.glsl +++ /dev/null @@ -1,62 +0,0 @@ -Geometry geometry; -Material material; -ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - -initGeometry(geometry, gl_FrontFacing); -initMaterial(material, geometry); - -// Direct Light -addTotalDirectRadiance(geometry, material, reflectedLight); - -// IBL diffuse -#ifdef SCENE_USE_SH - vec3 irradiance = getLightProbeIrradiance(scene_EnvSH, geometry.normal); - irradiance *= scene_EnvMapLight.diffuseIntensity; -#else - vec3 irradiance = scene_EnvMapLight.diffuse * scene_EnvMapLight.diffuseIntensity; - irradiance *= PI; -#endif - -reflectedLight.indirectDiffuse += material.diffuseAO * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor ); - -// IBL specular -vec3 radiance = getLightProbeRadiance(geometry, geometry.normal, material.roughness, int(scene_EnvMapLight.mipMapLevel), scene_EnvMapLight.specularIntensity); -float radianceAttenuation = 1.0; - -// IBL Clear Coat -#ifdef MATERIAL_ENABLE_CLEAR_COAT - vec3 clearCoatRadiance = getLightProbeRadiance( geometry, geometry.clearCoatNormal, material.clearCoatRoughness, int(scene_EnvMapLight.mipMapLevel), scene_EnvMapLight.specularIntensity ); - - reflectedLight.indirectSpecular += material.specularAO * clearCoatRadiance * material.clearCoat * envBRDFApprox(vec3( 0.04 ), 1.0, material.clearCoatRoughness, geometry.clearCoatDotNV); - radianceAttenuation -= material.clearCoat * F_Schlick(0.04, 1.0, geometry.clearCoatDotNV); -#endif - -reflectedLight.indirectSpecular += material.specularAO * radianceAttenuation * radiance * envBRDFApprox(material.resolvedSpecularF0, material.specularF90, material.roughness, geometry.dotNV) * material.energyCompensation; - - -// IBL Sheen -evaluateSheenIBL(geometry, material, radianceAttenuation, reflectedLight.indirectDiffuse, reflectedLight.indirectSpecular); - - -// Final color -vec3 totalDiffuseColor = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; -vec3 totalSpecularColor = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - -#ifdef MATERIAL_ENABLE_TRANSMISSION - vec3 refractionTransmitted = evaluateTransmission(geometry, material); - totalDiffuseColor = mix(totalDiffuseColor, refractionTransmitted, material.transmission); -#endif - -vec4 finalColor = vec4(totalDiffuseColor + totalSpecularColor, material.opacity); - - -// Emissive -vec3 emissiveRadiance = material_EmissiveColor; -#ifdef MATERIAL_HAS_EMISSIVETEXTURE - emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_uv).rgb; -#endif - -finalColor.rgb += emissiveRadiance; - - -gl_FragColor = finalColor; diff --git a/packages/core/src/shaderlib/pbr/pbr_frag_define.glsl b/packages/core/src/shaderlib/pbr/pbr_frag_define.glsl deleted file mode 100644 index 39cd4d7442..0000000000 --- a/packages/core/src/shaderlib/pbr/pbr_frag_define.glsl +++ /dev/null @@ -1,177 +0,0 @@ -#define MIN_PERCEPTUAL_ROUGHNESS 0.045 -#define MIN_ROUGHNESS 0.002025 - -uniform float material_AlphaCutoff; -uniform vec4 material_BaseColor; -uniform float material_Metal; -uniform float material_Roughness; -uniform float material_IOR; -uniform vec3 material_EmissiveColor; -uniform float material_NormalIntensity; -uniform float material_OcclusionIntensity; -uniform float material_OcclusionTextureCoord; -uniform float material_SpecularIntensity; -uniform vec3 material_SpecularColor; - -#ifdef MATERIAL_ENABLE_CLEAR_COAT - uniform float material_ClearCoat; - uniform float material_ClearCoatRoughness; - - #ifdef MATERIAL_HAS_CLEAR_COAT_TEXTURE - uniform sampler2D material_ClearCoatTexture; - #endif - - #ifdef MATERIAL_HAS_CLEAR_COAT_ROUGHNESS_TEXTURE - uniform sampler2D material_ClearCoatRoughnessTexture; - #endif - - #ifdef MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE - uniform sampler2D material_ClearCoatNormalTexture; - #endif -#endif - -#ifdef MATERIAL_ENABLE_ANISOTROPY - uniform vec3 material_AnisotropyInfo; - #ifdef MATERIAL_HAS_ANISOTROPY_TEXTURE - uniform sampler2D material_AnisotropyTexture; - #endif -#endif - -// Texture -#ifdef MATERIAL_HAS_BASETEXTURE - uniform sampler2D material_BaseTexture; -#endif - -#ifdef MATERIAL_HAS_NORMALTEXTURE - uniform sampler2D material_NormalTexture; -#endif - -#ifdef MATERIAL_HAS_EMISSIVETEXTURE - uniform sampler2D material_EmissiveTexture; -#endif - -#ifdef MATERIAL_HAS_ROUGHNESS_METALLIC_TEXTURE - uniform sampler2D material_RoughnessMetallicTexture; -#endif - -#ifdef MATERIAL_HAS_SPECULAR_TEXTURE - uniform sampler2D material_SpecularIntensityTexture; -#endif - -#ifdef MATERIAL_HAS_SPECULAR_COLOR_TEXTURE - uniform sampler2D material_SpecularColorTexture; -#endif - -#ifdef MATERIAL_HAS_OCCLUSION_TEXTURE - uniform sampler2D material_OcclusionTexture; -#endif - - -#ifdef MATERIAL_ENABLE_SHEEN - uniform float material_SheenRoughness; - uniform vec3 material_SheenColor; - #ifdef MATERIAL_HAS_SHEEN_TEXTURE - uniform sampler2D material_SheenTexture; - #endif - - #ifdef MATERIAL_HAS_SHEEN_ROUGHNESS_TEXTURE - uniform sampler2D material_SheenRoughnessTexture; - #endif -#endif - - -#ifdef MATERIAL_ENABLE_IRIDESCENCE - uniform vec4 material_IridescenceInfo; - #ifdef MATERIAL_HAS_IRIDESCENCE_THICKNESS_TEXTURE - uniform sampler2D material_IridescenceThicknessTexture; - #endif - - #ifdef MATERIAL_HAS_IRIDESCENCE_TEXTURE - uniform sampler2D material_IridescenceTexture; - #endif -#endif - -#ifdef MATERIAL_ENABLE_TRANSMISSION - uniform float material_Transmission; - #ifdef MATERIAL_HAS_TRANSMISSION_TEXTURE - uniform sampler2D material_TransmissionTexture; - #endif - - #ifdef MATERIAL_HAS_THICKNESS - uniform vec3 material_AttenuationColor; - uniform float material_AttenuationDistance; - uniform float material_Thickness; - - #ifdef MATERIAL_HAS_THICKNESS_TEXTURE - uniform sampler2D material_ThicknessTexture; - #endif - #endif -#endif - -// Runtime -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; - -struct Geometry { - vec3 position; - vec3 normal; - vec3 viewDir; - float dotNV; - - #ifdef MATERIAL_ENABLE_CLEAR_COAT - vec3 clearCoatNormal; - float clearCoatDotNV; - #endif - - #ifdef MATERIAL_ENABLE_ANISOTROPY - vec3 anisotropicT; - vec3 anisotropicB; - vec3 anisotropicN; - float anisotropy; - #endif -}; - -struct Material { - vec3 diffuseColor; - float roughness; - vec3 specularF0; - vec3 resolvedSpecularF0; - float specularF90; - float specularIntensity; - vec3 specularColor; - float opacity; - float diffuseAO; - float specularAO; - vec3 envSpecularDFG; - vec3 energyCompensation; // Multi-scattering energy compensation factor - float IOR; - - #ifdef MATERIAL_ENABLE_CLEAR_COAT - float clearCoat; - float clearCoatRoughness; - #endif - - #ifdef MATERIAL_ENABLE_IRIDESCENCE - float iridescenceIOR; - float iridescenceFactor; - float iridescenceThickness; - vec3 iridescenceSpecularColor; - #endif - - #ifdef MATERIAL_ENABLE_SHEEN - float sheenRoughness; - vec3 sheenColor; - float sheenScaling; - float approxIBLSheenDG; - #endif - - #ifdef MATERIAL_ENABLE_TRANSMISSION - vec3 absorptionCoefficient; - float transmission; - float thickness; - #endif -}; diff --git a/packages/core/src/shaderlib/pbr/pbr_helper.glsl b/packages/core/src/shaderlib/pbr/pbr_helper.glsl deleted file mode 100644 index 6203e7d917..0000000000 --- a/packages/core/src/shaderlib/pbr/pbr_helper.glsl +++ /dev/null @@ -1,258 +0,0 @@ -#include -#include -#include - -// direct + indirect -#include -#include - -uniform sampler2D camera_AOTexture; - -float evaluateAmbientOcclusion(vec2 uv) -{ - #ifdef MATERIAL_IS_TRANSPARENT - return 1.0; - #else - return texture2D(camera_AOTexture, uv).r; - #endif -} - - -float computeSpecularOcclusion(float ambientOcclusion, float roughness, float dotNV ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -} - -float getAARoughnessFactor(vec3 normal) { - // Kaplanyan 2016, "Stable specular highlights" - // Tokuyoshi 2017, "Error Reduction and Simplification for Shading Anti-Aliasing" - // Tokuyoshi and Kaplanyan 2019, "Improved Geometric Specular Antialiasing" - #ifdef HAS_DERIVATIVES - vec3 dxy = max( abs(dFdx(normal)), abs(dFdy(normal)) ); - return max( max(dxy.x, dxy.y), dxy.z ); - #else - return 0.0; - #endif -} - -#ifdef MATERIAL_ENABLE_ANISOTROPY - // Aniso Bent Normals - // Mc Alley https://www.gdcvault.com/play/1022235/Rendering-the-World-of-Far - vec3 getAnisotropicBentNormal(Geometry geometry, vec3 n, float roughness) { - vec3 anisotropyDirection = geometry.anisotropy >= 0.0 ? geometry.anisotropicB : geometry.anisotropicT; - vec3 anisotropicTangent = cross(anisotropyDirection, geometry.viewDir); - vec3 anisotropicNormal = cross(anisotropicTangent, anisotropyDirection); - // reduce stretching for (roughness < 0.2), refer to https://advances.realtimerendering.com/s2018/Siggraph%202018%20HDRP%20talk_with%20notes.pdf 80 - vec3 bentNormal = normalize( mix(n, anisotropicNormal, abs(geometry.anisotropy) * saturate( 5.0 * roughness)) ); - - return bentNormal; - } -#endif - -void initGeometry(out Geometry geometry, bool isFrontFacing){ - geometry.position = v_pos; - #ifdef CAMERA_ORTHOGRAPHIC - geometry.viewDir = -camera_Forward; - #else - geometry.viewDir = normalize(camera_Position - v_pos); - #endif - #if defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) - mat3 tbn = getTBN(isFrontFacing); - #endif - - #ifdef MATERIAL_HAS_NORMALTEXTURE - geometry.normal = getNormalByNormalTexture(tbn, material_NormalTexture, material_NormalIntensity, v_uv, isFrontFacing); - #else - geometry.normal = getNormal(isFrontFacing); - #endif - - geometry.dotNV = saturate( dot(geometry.normal, geometry.viewDir) ); - - - #ifdef MATERIAL_ENABLE_CLEAR_COAT - #ifdef MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE - geometry.clearCoatNormal = getNormalByNormalTexture(tbn, material_ClearCoatNormalTexture, material_NormalIntensity, v_uv, isFrontFacing); - #else - geometry.clearCoatNormal = getNormal(isFrontFacing); - #endif - geometry.clearCoatDotNV = saturate( dot(geometry.clearCoatNormal, geometry.viewDir) ); - #endif - - #ifdef MATERIAL_ENABLE_ANISOTROPY - float anisotropy = material_AnisotropyInfo.z; - vec3 anisotropicDirection = vec3(material_AnisotropyInfo.xy, 0.0); - #ifdef MATERIAL_HAS_ANISOTROPY_TEXTURE - vec3 anisotropyTextureInfo = texture2D( material_AnisotropyTexture, v_uv ).rgb; - anisotropy *= anisotropyTextureInfo.b; - anisotropicDirection.xy *= anisotropyTextureInfo.rg * 2.0 - 1.0; - #endif - - geometry.anisotropy = anisotropy; - geometry.anisotropicT = normalize(tbn * anisotropicDirection); - geometry.anisotropicB = normalize(cross(geometry.normal, geometry.anisotropicT)); - #endif -} - -void initMaterial(out Material material, inout Geometry geometry){ - vec4 baseColor = material_BaseColor; - float metal = material_Metal; - float roughness = material_Roughness; - float alphaCutoff = material_AlphaCutoff; - material.IOR = material_IOR; - - #ifdef MATERIAL_HAS_BASETEXTURE - baseColor *= texture2DSRGB(material_BaseTexture, v_uv); - #endif - - #ifdef RENDERER_ENABLE_VERTEXCOLOR - baseColor *= v_color; - #endif - - - #ifdef MATERIAL_IS_ALPHA_CUTOFF - if( baseColor.a < alphaCutoff ) { - discard; - } - #endif - - #ifdef MATERIAL_HAS_ROUGHNESS_METALLIC_TEXTURE - vec4 metalRoughMapColor = texture2D( material_RoughnessMetallicTexture, v_uv ); - roughness *= metalRoughMapColor.g; - metal *= metalRoughMapColor.b; - #endif - - // Specular - material.specularIntensity = material_SpecularIntensity; - material.specularColor = material_SpecularColor; - #ifdef MATERIAL_HAS_SPECULAR_TEXTURE - material.specularIntensity *= texture2D( material_SpecularIntensityTexture, v_uv ).a; - #endif - - #ifdef MATERIAL_ENABLE_CLEAR_COAT - material.clearCoat = material_ClearCoat; - material.clearCoatRoughness = material_ClearCoatRoughness; - #ifdef MATERIAL_HAS_CLEAR_COAT_TEXTURE - material.clearCoat *= texture2D( material_ClearCoatTexture, v_uv ).r; - #endif - #ifdef MATERIAL_HAS_CLEAR_COAT_ROUGHNESS_TEXTURE - material.clearCoatRoughness *= texture2D( material_ClearCoatRoughnessTexture, v_uv ).g; - #endif - material.clearCoat = saturate( material.clearCoat ); - material.clearCoatRoughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(material.clearCoatRoughness + getAARoughnessFactor(geometry.clearCoatNormal), 1.0)); - #endif - - #ifdef MATERIAL_IS_TRANSPARENT - material.opacity = baseColor.a; - #else - material.opacity = 1.0; - #endif - - material.roughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(roughness + getAARoughnessFactor(geometry.normal), 1.0)); - - #ifdef MATERIAL_ENABLE_ANISOTROPY - geometry.anisotropicN = getAnisotropicBentNormal(geometry, geometry.normal, material.roughness); - #endif - - vec3 dielectricBaseF0 = vec3(pow2( (material.IOR - 1.0) / (material.IOR + 1.0) )); - vec3 dielectricF0 = min(dielectricBaseF0 * material.specularColor , vec3(1.0)) * material.specularIntensity; - float dielectricF90 = material.specularIntensity; - - material.specularF0 = mix(dielectricF0, baseColor.rgb, metal); - material.specularF90 = mix(dielectricF90, 1.0, metal); - material.resolvedSpecularF0 = material.specularF0; - - // Simplify: albedoColor * mix((1.0 - max(max(dielectricF0.r,dielectricF0.g),dielectricF0.b)), 0.0, metallic); - material.diffuseColor = baseColor.rgb * (1.0 - metal) * (1.0 - max(max(dielectricF0.r,dielectricF0.g),dielectricF0.b)); - // Environment BRDF - vec2 dfg = envDFGApprox(material.roughness, geometry.dotNV); - - // AO - float diffuseAO = 1.0; - float specularAO = 1.0; - - #ifdef MATERIAL_HAS_OCCLUSION_TEXTURE - vec2 aoUV = v_uv; - #ifdef RENDERER_HAS_UV1 - if(material_OcclusionTextureCoord == 1.0){ - aoUV = v_uv1; - } - #endif - diffuseAO = ((texture2D(material_OcclusionTexture, aoUV)).r - 1.0) * material_OcclusionIntensity + 1.0; - #endif - - #ifdef SCENE_ENABLE_AMBIENT_OCCLUSION - float ambientAO = evaluateAmbientOcclusion((v_PositionCS.xy / v_PositionCS.w) * 0.5 + 0.5); - diffuseAO = min(diffuseAO, ambientAO); - #endif - - #if (defined(MATERIAL_HAS_OCCLUSION_TEXTURE) || defined(SCENE_ENABLE_AMBIENT_OCCLUSION))&& defined(SCENE_USE_SPECULAR_ENV) - specularAO = saturate( pow( geometry.dotNV + diffuseAO, exp2( - 16.0 * material.roughness - 1.0 ) ) - 1.0 + diffuseAO ); - #endif - - material.diffuseAO = diffuseAO; - material.specularAO = specularAO; - - // Sheen - #ifdef MATERIAL_ENABLE_SHEEN - vec3 sheenColor = material_SheenColor; - #ifdef MATERIAL_HAS_SHEEN_TEXTURE - sheenColor *= texture2DSRGB(material_SheenTexture, v_uv).rgb; - #endif - material.sheenColor = sheenColor; - - material.sheenRoughness = material_SheenRoughness; - #ifdef MATERIAL_HAS_SHEEN_ROUGHNESS_TEXTURE - material.sheenRoughness *= texture2D(material_SheenRoughnessTexture, v_uv).a; - #endif - - material.sheenRoughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(material.sheenRoughness + getAARoughnessFactor(geometry.normal), 1.0)); - material.approxIBLSheenDG = prefilteredSheenDFG(geometry.dotNV, material.sheenRoughness); - material.sheenScaling = 1.0 - material.approxIBLSheenDG * max(max(material.sheenColor.r, material.sheenColor.g), material.sheenColor.b); - #endif - - // Iridescence - #ifdef MATERIAL_ENABLE_IRIDESCENCE - material.iridescenceFactor = material_IridescenceInfo.x; - material.iridescenceIOR = material_IridescenceInfo.y; - - #ifdef MATERIAL_HAS_IRIDESCENCE_THICKNESS_TEXTURE - float iridescenceThicknessWeight = texture2D( material_IridescenceThicknessTexture, v_uv).g; - material.iridescenceThickness = mix(material_IridescenceInfo.z, material_IridescenceInfo.w, iridescenceThicknessWeight); - #else - material.iridescenceThickness = material_IridescenceInfo.w; - #endif - - #ifdef MATERIAL_HAS_IRIDESCENCE_TEXTURE - material.iridescenceFactor *= texture2D( material_IridescenceTexture, v_uv).r; - #endif - - #ifdef MATERIAL_ENABLE_IRIDESCENCE - float topIOR = 1.0; - material.iridescenceSpecularColor = evalIridescenceSpecular(topIOR, geometry.dotNV, material.iridescenceIOR, material.specularF0, material.specularF90, material.iridescenceThickness); - material.resolvedSpecularF0 = mix(material.resolvedSpecularF0, material.iridescenceSpecularColor, material.iridescenceFactor); - #endif - #endif - - material.envSpecularDFG = material.resolvedSpecularF0 * dfg.x + material.specularF90 * dfg.y; - - // Multi-scattering energy compensation - // Ref: Kulla & Conty 2017, "Revisiting Physically Based Shading at Imageworks" - // Ref: Lagarde & Golubev 2018, simplified multiplier approach - material.energyCompensation = 1.0 + material.resolvedSpecularF0 * (1.0 / max(dfg.x + dfg.y, EPSILON) - 1.0); - - // Transmission - #ifdef MATERIAL_ENABLE_TRANSMISSION - material.transmission = material_Transmission; - #ifdef MATERIAL_HAS_TRANSMISSION_TEXTURE - material.transmission *= texture2D(material_TransmissionTexture, v_uv).r; - #endif - - #ifdef MATERIAL_HAS_THICKNESS - material.absorptionCoefficient = -log(material_AttenuationColor + HALF_EPS) / max(HALF_EPS, material_AttenuationDistance); - material.thickness = max(material_Thickness, 0.0001); - #ifdef MATERIAL_HAS_THICKNESS_TEXTURE - material.thickness *= texture2D( material_ThicknessTexture, v_uv).g; - #endif - #endif - #endif -} - diff --git a/packages/core/src/shaderlib/pbr/refraction.glsl b/packages/core/src/shaderlib/pbr/refraction.glsl deleted file mode 100644 index 1755cf1f2a..0000000000 --- a/packages/core/src/shaderlib/pbr/refraction.glsl +++ /dev/null @@ -1,40 +0,0 @@ -#ifdef MATERIAL_ENABLE_TRANSMISSION - struct RefractionModelResult { - float transmissionLength; // length of the transmission during refraction through the shape - vec3 positionExit; // out ray position - // vec3 directionExit; // out ray direction - }; - - //https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@15.0/manual/refraction-models.html - void refractionModelSphere(vec3 V, vec3 positionWS, vec3 normalWS, float ior, float thickness, out RefractionModelResult ray) { - // Refracted ray - vec3 R1 = refract(V, normalWS, 1.0 / ior); - // Center of the tangent sphere - // vec3 C = positionWS - normalWS * thickness * 0.5; - - // Second refraction (tangent sphere out) - float dist = dot(-normalWS, R1) * thickness; - // Out hit point in the tangent sphere - vec3 P1 = positionWS + R1 * dist; - // Out normal - // vec3 N1 = safeNormalize(C - P1); - // Out refracted ray - // vec3 R2 = refract(R1, N1, ior); - - ray.transmissionLength = dist; - ray.positionExit = P1; - // ray.directionExit = R2; - } - - void refractionModelPlanar(vec3 V, vec3 positionWS, vec3 normalWS, float ior, float thickness, out RefractionModelResult ray) { - // Refracted ray - vec3 R = refract(V, normalWS, 1.0 / ior); - // Optical depth within the thin plane - float dist = thickness / max(dot(-normalWS, R), 1e-5f); - - ray.transmissionLength = dist; - ray.positionExit = vec3(positionWS + R * dist); - // ray.directionExit = V; - } - -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/position_vert.glsl b/packages/core/src/shaderlib/position_vert.glsl deleted file mode 100644 index 75bc9c5bd9..0000000000 --- a/packages/core/src/shaderlib/position_vert.glsl +++ /dev/null @@ -1 +0,0 @@ - gl_Position = renderer_MVPMat * position; \ No newline at end of file diff --git a/packages/core/src/shaderlib/shadow/ShadowCoord.glsl b/packages/core/src/shaderlib/shadow/ShadowCoord.glsl deleted file mode 100644 index 54972cdf05..0000000000 --- a/packages/core/src/shaderlib/shadow/ShadowCoord.glsl +++ /dev/null @@ -1,66 +0,0 @@ - -uniform mat4 scene_ShadowMatrices[SCENE_SHADOW_CASCADED_COUNT + 1]; -uniform vec4 scene_ShadowSplitSpheres[4]; - -mediump int computeCascadeIndex(vec3 positionWS) { - vec3 fromCenter0 = positionWS - scene_ShadowSplitSpheres[0].xyz; - vec3 fromCenter1 = positionWS - scene_ShadowSplitSpheres[1].xyz; - vec3 fromCenter2 = positionWS - scene_ShadowSplitSpheres[2].xyz; - vec3 fromCenter3 = positionWS - scene_ShadowSplitSpheres[3].xyz; - - mediump vec4 comparison = vec4( - dot(fromCenter0, fromCenter0) < scene_ShadowSplitSpheres[0].w, - dot(fromCenter1, fromCenter1) < scene_ShadowSplitSpheres[1].w, - dot(fromCenter2, fromCenter2) < scene_ShadowSplitSpheres[2].w, - dot(fromCenter3, fromCenter3) < scene_ShadowSplitSpheres[3].w); - comparison.yzw = clamp(comparison.yzw - comparison.xyz,0.0,1.0);//keep the nearest - mediump vec4 indexCoefficient = vec4(4.0,3.0,2.0,1.0); - mediump int index = 4 - int(dot(comparison, indexCoefficient)); - return index; -} - -vec3 getShadowCoord() { - #if SCENE_SHADOW_CASCADED_COUNT == 1 - mediump int cascadeIndex = 0; - #else - mediump int cascadeIndex = computeCascadeIndex(v_pos); - #endif - - #ifdef GRAPHICS_API_WEBGL2 - mat4 shadowMatrix = scene_ShadowMatrices[cascadeIndex]; - #else - mat4 shadowMatrix; - #if SCENE_SHADOW_CASCADED_COUNT == 4 - if (cascadeIndex == 0) { - shadowMatrix = scene_ShadowMatrices[0]; - } else if (cascadeIndex == 1) { - shadowMatrix = scene_ShadowMatrices[1]; - } else if (cascadeIndex == 2) { - shadowMatrix = scene_ShadowMatrices[2]; - } else if (cascadeIndex == 3) { - shadowMatrix = scene_ShadowMatrices[3]; - } else { - shadowMatrix = scene_ShadowMatrices[4]; - } - #endif - #if SCENE_SHADOW_CASCADED_COUNT == 2 - if (cascadeIndex == 0) { - shadowMatrix = scene_ShadowMatrices[0]; - } else if (cascadeIndex == 1) { - shadowMatrix = scene_ShadowMatrices[1]; - } else { - shadowMatrix = scene_ShadowMatrices[2]; - } - #endif - #if SCENE_SHADOW_CASCADED_COUNT == 1 - if (cascadeIndex == 0) { - shadowMatrix = scene_ShadowMatrices[0]; - } else { - shadowMatrix = scene_ShadowMatrices[1]; - } - #endif - #endif - - vec4 shadowCoord = shadowMatrix * vec4(v_pos, 1.0); - return shadowCoord.xyz; -} diff --git a/packages/core/src/shaderlib/shadow/ShadowFragmentDeclaration.glsl b/packages/core/src/shaderlib/shadow/ShadowFragmentDeclaration.glsl deleted file mode 100644 index 1fa6e6e22a..0000000000 --- a/packages/core/src/shaderlib/shadow/ShadowFragmentDeclaration.glsl +++ /dev/null @@ -1,109 +0,0 @@ -#if defined(SCENE_SHADOW_TYPE) && defined(RENDERER_IS_RECEIVE_SHADOWS) - #define SCENE_IS_CALCULATE_SHADOWS -#endif - -#ifdef SCENE_IS_CALCULATE_SHADOWS - #if SCENE_SHADOW_CASCADED_COUNT == 1 - varying vec3 v_shadowCoord; - #else - #include - #endif - - // intensity, null, fadeScale, fadeBias - uniform vec4 scene_ShadowInfo; - uniform vec4 scene_ShadowMapSize; - - #ifdef GRAPHICS_API_WEBGL2 - uniform mediump sampler2DShadow scene_ShadowMap; - #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) textureLod(textureName, coord3 , 0.0) - #define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2DShadow shadowMap - #else - uniform sampler2D scene_ShadowMap; - #ifdef ENGINE_NO_DEPTH_TEXTURE - const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0*256.0), 1.0/(256.0*256.0*256.0)); - /** - * Unpack depth value. - */ - float unpack(const in vec4 rgbaDepth) { - return dot(rgbaDepth, bitShift); - } - #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (unpack(texture2D(textureName, coord3.xy)) < coord3.z ? 0.0 : 1.0) - #else - #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (texture2D(textureName, coord3.xy).r < coord3.z ? 0.0 : 1.0) - #endif - #define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2D shadowMap - #endif - - #if SCENE_SHADOW_TYPE == 2 - float sampleShadowMapFiltered4(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoord, vec4 shadowMapSize) { - float attenuation; - vec4 attenuation4; - vec2 offset=shadowMapSize.xy/2.0; - vec3 shadowCoord0=shadowCoord + vec3(-offset,0.0); - vec3 shadowCoord1=shadowCoord + vec3(offset.x,-offset.y,0.0); - vec3 shadowCoord2=shadowCoord + vec3(-offset.x,offset.y,0.0); - vec3 shadowCoord3=shadowCoord + vec3(offset,0.0); - attenuation4.x = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord0); - attenuation4.y = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord1); - attenuation4.z = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord2); - attenuation4.w = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord3); - attenuation = dot(attenuation4, vec4(0.25)); - return attenuation; - } - #endif - - #if SCENE_SHADOW_TYPE == 3 - #include - - float sampleShadowMapFiltered9(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoord, vec4 shadowmapSize) { - float attenuation; - float fetchesWeights[9]; - vec2 fetchesUV[9]; - sampleShadowComputeSamplesTent5x5(shadowmapSize, shadowCoord.xy, fetchesWeights, fetchesUV); - attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[0].xy, shadowCoord.z)); - attenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[1].xy, shadowCoord.z)); - attenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[2].xy, shadowCoord.z)); - attenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[3].xy, shadowCoord.z)); - attenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[4].xy, shadowCoord.z)); - attenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[5].xy, shadowCoord.z)); - attenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[6].xy, shadowCoord.z)); - attenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[7].xy, shadowCoord.z)); - attenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[8].xy, shadowCoord.z)); - return attenuation; - } - #endif - - - float getShadowFade(vec3 positionWS){ - vec3 camToPixel = positionWS - camera_Position; - float distanceCamToPixel2 = dot(camToPixel, camToPixel); - return saturate( distanceCamToPixel2 * scene_ShadowInfo.z + scene_ShadowInfo.w ); - } - - float sampleShadowMap() { - #if SCENE_SHADOW_CASCADED_COUNT == 1 - vec3 shadowCoord = v_shadowCoord; - #else - vec3 shadowCoord = getShadowCoord(); - #endif - - float attenuation = 1.0; - if(shadowCoord.z > 0.0 && shadowCoord.z < 1.0) { - #if SCENE_SHADOW_TYPE == 1 - attenuation = SAMPLE_TEXTURE2D_SHADOW(scene_ShadowMap, shadowCoord); - #endif - - #if SCENE_SHADOW_TYPE == 2 - attenuation = sampleShadowMapFiltered4(scene_ShadowMap, shadowCoord, scene_ShadowMapSize); - #endif - - #if SCENE_SHADOW_TYPE == 3 - attenuation = sampleShadowMapFiltered9(scene_ShadowMap, shadowCoord, scene_ShadowMapSize); - #endif - - float shadowFade = getShadowFade(v_pos); - attenuation = mix(1.0, mix(attenuation, 1.0, shadowFade), scene_ShadowInfo.x); - } - return attenuation; - } -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/shadow/ShadowVertex.glsl b/packages/core/src/shaderlib/shadow/ShadowVertex.glsl deleted file mode 100644 index 655e9f54d4..0000000000 --- a/packages/core/src/shaderlib/shadow/ShadowVertex.glsl +++ /dev/null @@ -1,5 +0,0 @@ -#ifdef SCENE_IS_CALCULATE_SHADOWS - #if SCENE_SHADOW_CASCADED_COUNT == 1 - v_shadowCoord = getShadowCoord(); - #endif -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/shadow/ShadowVertexDeclaration.glsl b/packages/core/src/shaderlib/shadow/ShadowVertexDeclaration.glsl deleted file mode 100644 index 9a5a6bdc77..0000000000 --- a/packages/core/src/shaderlib/shadow/ShadowVertexDeclaration.glsl +++ /dev/null @@ -1,10 +0,0 @@ -#if defined(SCENE_SHADOW_TYPE) && defined(RENDERER_IS_RECEIVE_SHADOWS) - #define SCENE_IS_CALCULATE_SHADOWS -#endif - -#ifdef SCENE_IS_CALCULATE_SHADOWS - #if SCENE_SHADOW_CASCADED_COUNT==1 - #include - varying vec3 v_shadowCoord; - #endif -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/shadow/index.ts b/packages/core/src/shaderlib/shadow/index.ts deleted file mode 100644 index a22b4fe044..0000000000 --- a/packages/core/src/shaderlib/shadow/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -import ShadowCoord from "./ShadowCoord.glsl"; -import ShadowFragmentDeclaration from "./ShadowFragmentDeclaration.glsl"; -import shadow_sample_tent from "./shadow_sample_tent.glsl"; -import ShadowVertexDeclaration from "./ShadowVertexDeclaration.glsl"; -import ShadowVertex from "./ShadowVertex.glsl"; - -export default { - ShadowCoord, - ShadowFragmentDeclaration, - shadow_sample_tent, - ShadowVertexDeclaration, - ShadowVertex -}; diff --git a/packages/core/src/shaderlib/shadow/shadow_sample_tent.glsl b/packages/core/src/shaderlib/shadow/shadow_sample_tent.glsl deleted file mode 100644 index db9418f5d4..0000000000 --- a/packages/core/src/shaderlib/shadow/shadow_sample_tent.glsl +++ /dev/null @@ -1,114 +0,0 @@ -// ------------------------------------------------------------------ -// PCF Filtering Tent Functions -// ------------------------------------------------------------------ - -// Assuming a isoceles right angled triangle of height "triangleHeight" (as drawn below). -// This function return the area of the triangle above the first texel(in Y the first texel). -// -// |\ <-- 45 degree slop isosceles right angled triangle -// | \ -// ---- <-- length of this side is "triangleHeight" -// _ _ _ _ <-- texels -float sampleShadowGetIRTriangleTexelArea(float triangleHeight) { - return triangleHeight - 0.5; -} - -// Assuming a isoceles triangle of 1.5 texels height and 3 texels wide lying on 4 texels. -// This function return the area of the triangle above each of those texels. -// | <-- offset from -0.5 to 0.5, 0 meaning triangle is exactly in the center -// / \ <-- 45 degree slop isosceles triangle (ie tent projected in 2D) -// / \ -// _ _ _ _ <-- texels -// X Y Z W <-- result indices (in computedArea.xyzw and computedAreaUncut.xyzw) -// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel. -void sampleShadowGetTexelAreasTent3x3(float offset, out vec4 computedArea, out vec4 computedAreaUncut) { - // Compute the exterior areas,a and h is same. - float a = offset + 0.5; - float offsetSquaredHalved = a * a * 0.5; - computedAreaUncut.x = computedArea.x = offsetSquaredHalved - offset; - computedAreaUncut.w = computedArea.w = offsetSquaredHalved; - - // Compute the middle areas - // For Y : We find the area in Y of as if the left section of the isoceles triangle would - // intersect the axis between Y and Z (ie where offset = 0). - computedAreaUncut.y = sampleShadowGetIRTriangleTexelArea(1.5 - offset); - // This area is superior to the one we are looking for if (offset < 0) thus we need to - // subtract the area of the triangle defined by (0,1.5-offset), (0,1.5+offset), (-offset,1.5). - float clampedOffsetLeft = min(offset,0.0); - float areaOfSmallLeftTriangle = clampedOffsetLeft * clampedOffsetLeft; - computedArea.y = computedAreaUncut.y - areaOfSmallLeftTriangle; - - // We do the same for the Z but with the right part of the isoceles triangle - computedAreaUncut.z = sampleShadowGetIRTriangleTexelArea(1.5 + offset); - float clampedOffsetRight = max(offset,0.0); - float areaOfSmallRightTriangle = clampedOffsetRight * clampedOffsetRight; - computedArea.z = computedAreaUncut.z - areaOfSmallRightTriangle; -} - -// Assuming a isoceles triangle of 2.5 texel height and 5 texels wide lying on 6 texels. -// This function return the weight of each texels area relative to the full triangle area. -// / \ -// _ _ _ _ _ _ <-- texels -// 0 1 2 3 4 5 <-- computed area indices (in texelsWeights[]) -// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel. -void sampleShadowGetTexelWeightsTent5x5(float offset, out vec3 texelsWeightsA, out vec3 texelsWeightsB) { - vec4 areaFrom3texelTriangle; - vec4 areaUncutFrom3texelTriangle; - sampleShadowGetTexelAreasTent3x3(offset, areaFrom3texelTriangle, areaUncutFrom3texelTriangle); - - // Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation. - // the 5 texel wide triangle can be seen as the 3 texel wide one but shifted up by one unit/texel. - // 0.16 is 1/(the triangle area) - texelsWeightsA.x = 0.16 * (areaFrom3texelTriangle.x); - texelsWeightsA.y = 0.16 * (areaUncutFrom3texelTriangle.y); - texelsWeightsA.z = 0.16 * (areaFrom3texelTriangle.y + 1.0); - texelsWeightsB.x = 0.16 * (areaFrom3texelTriangle.z + 1.0); - texelsWeightsB.y = 0.16 * (areaUncutFrom3texelTriangle.z); - texelsWeightsB.z = 0.16 * (areaFrom3texelTriangle.w); -} - -// 5x5 Tent filter (45 degree sloped triangles in U and V) -void sampleShadowComputeSamplesTent5x5(vec4 shadowMapTextureTexelSize, vec2 coord, out float fetchesWeights[9], out vec2 fetchesUV[9]) -{ - // tent base is 5x5 base thus covering from 25 to 36 texels, thus we need 9 bilinear PCF fetches - vec2 tentCenterInTexelSpace = coord.xy * shadowMapTextureTexelSize.zw; - vec2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5); - vec2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace; - - // find the weight of each texel based on the area of a 45 degree slop tent above each of them. - vec3 texelsWeightsUA, texelsWeightsUB; - vec3 texelsWeightsVA, texelsWeightsVB; - sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsUA, texelsWeightsUB); - sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsVA, texelsWeightsVB); - - // each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels - vec3 fetchesWeightsU = vec3(texelsWeightsUA.xz, texelsWeightsUB.y) + vec3(texelsWeightsUA.y, texelsWeightsUB.xz); - vec3 fetchesWeightsV = vec3(texelsWeightsVA.xz, texelsWeightsVB.y) + vec3(texelsWeightsVA.y, texelsWeightsVB.xz); - - // move the PCF bilinear fetches to respect texels weights - vec3 fetchesOffsetsU = vec3(texelsWeightsUA.y, texelsWeightsUB.xz) / fetchesWeightsU.xyz + vec3(-2.5,-0.5,1.5); - vec3 fetchesOffsetsV = vec3(texelsWeightsVA.y, texelsWeightsVB.xz) / fetchesWeightsV.xyz + vec3(-2.5,-0.5,1.5); - fetchesOffsetsU *= shadowMapTextureTexelSize.xxx; - fetchesOffsetsV *= shadowMapTextureTexelSize.yyy; - - vec2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTextureTexelSize.xy; - fetchesUV[0] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.x); - fetchesUV[1] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.x); - fetchesUV[2] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.x); - fetchesUV[3] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.y); - fetchesUV[4] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.y); - fetchesUV[5] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.y); - fetchesUV[6] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.z); - fetchesUV[7] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.z); - fetchesUV[8] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.z); - - fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x; - fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x; - fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x; - fetchesWeights[3] = fetchesWeightsU.x * fetchesWeightsV.y; - fetchesWeights[4] = fetchesWeightsU.y * fetchesWeightsV.y; - fetchesWeights[5] = fetchesWeightsU.z * fetchesWeightsV.y; - fetchesWeights[6] = fetchesWeightsU.x * fetchesWeightsV.z; - fetchesWeights[7] = fetchesWeightsU.y * fetchesWeightsV.z; - fetchesWeights[8] = fetchesWeightsU.z * fetchesWeightsV.z; -} \ No newline at end of file diff --git a/packages/core/src/shaderlib/skinning_vert.glsl b/packages/core/src/shaderlib/skinning_vert.glsl deleted file mode 100644 index 57a7514406..0000000000 --- a/packages/core/src/shaderlib/skinning_vert.glsl +++ /dev/null @@ -1,29 +0,0 @@ -#ifdef RENDERER_HAS_SKIN - - #ifdef RENDERER_USE_JOINT_TEXTURE - mat4 skinMatrix = - WEIGHTS_0.x * getJointMatrix(renderer_JointSampler, JOINTS_0.x ) + - WEIGHTS_0.y * getJointMatrix(renderer_JointSampler, JOINTS_0.y ) + - WEIGHTS_0.z * getJointMatrix(renderer_JointSampler, JOINTS_0.z ) + - WEIGHTS_0.w * getJointMatrix(renderer_JointSampler, JOINTS_0.w ); - - #else - mat4 skinMatrix = - WEIGHTS_0.x * renderer_JointMatrix[ int( JOINTS_0.x ) ] + - WEIGHTS_0.y * renderer_JointMatrix[ int( JOINTS_0.y ) ] + - WEIGHTS_0.z * renderer_JointMatrix[ int( JOINTS_0.z ) ] + - WEIGHTS_0.w * renderer_JointMatrix[ int( JOINTS_0.w ) ]; - #endif - - position = skinMatrix * position; - - #if defined(RENDERER_HAS_NORMAL) && !defined(MATERIAL_OMIT_NORMAL) - mat3 skinNormalMatrix = INVERSE_MAT(mat3(skinMatrix)); - normal = normal * skinNormalMatrix; - #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) ) - tangent.xyz = tangent.xyz * skinNormalMatrix; - #endif - - #endif - -#endif diff --git a/packages/core/src/shaderlib/transform_declare.glsl b/packages/core/src/shaderlib/transform_declare.glsl deleted file mode 100644 index 00e1d5edba..0000000000 --- a/packages/core/src/shaderlib/transform_declare.glsl +++ /dev/null @@ -1,7 +0,0 @@ -uniform mat4 renderer_LocalMat; -uniform mat4 renderer_ModelMat; -uniform mat4 camera_ViewMat; -uniform mat4 camera_ProjMat; -uniform mat4 renderer_MVMat; -uniform mat4 renderer_MVPMat; -uniform mat4 renderer_NormalMat; \ No newline at end of file diff --git a/packages/core/src/shaderlib/uv_share.glsl b/packages/core/src/shaderlib/uv_share.glsl deleted file mode 100644 index 590922a16b..0000000000 --- a/packages/core/src/shaderlib/uv_share.glsl +++ /dev/null @@ -1,5 +0,0 @@ -varying vec2 v_uv; - -#ifdef RENDERER_HAS_UV1 - varying vec2 v_uv1; -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/uv_vert.glsl b/packages/core/src/shaderlib/uv_vert.glsl deleted file mode 100644 index 3daaefea12..0000000000 --- a/packages/core/src/shaderlib/uv_vert.glsl +++ /dev/null @@ -1,14 +0,0 @@ -#ifdef RENDERER_HAS_UV - v_uv = TEXCOORD_0; -#else - // may need this calculate normal - v_uv = vec2( 0., 0. ); -#endif - -#ifdef RENDERER_HAS_UV1 - v_uv1 = TEXCOORD_1; -#endif - -#ifdef MATERIAL_NEED_TILING_OFFSET - v_uv = v_uv * material_TilingOffset.xy + material_TilingOffset.zw; -#endif \ No newline at end of file diff --git a/packages/core/src/shaderlib/worldpos_share.glsl b/packages/core/src/shaderlib/worldpos_share.glsl deleted file mode 100644 index ca1b63f460..0000000000 --- a/packages/core/src/shaderlib/worldpos_share.glsl +++ /dev/null @@ -1,3 +0,0 @@ -#ifdef MATERIAL_NEED_WORLD_POS - varying vec3 v_pos; -#endif diff --git a/packages/core/src/shaderlib/worldpos_vert.glsl b/packages/core/src/shaderlib/worldpos_vert.glsl deleted file mode 100644 index cf0598025a..0000000000 --- a/packages/core/src/shaderlib/worldpos_vert.glsl +++ /dev/null @@ -1,4 +0,0 @@ -#ifdef MATERIAL_NEED_WORLD_POS - vec4 temp_pos = renderer_ModelMat * position; - v_pos = temp_pos.xyz / temp_pos.w; -#endif diff --git a/packages/core/src/sky/SkyBoxMaterial.ts b/packages/core/src/sky/SkyBoxMaterial.ts index 608f7d3fc9..964c1f14c6 100644 --- a/packages/core/src/sky/SkyBoxMaterial.ts +++ b/packages/core/src/sky/SkyBoxMaterial.ts @@ -65,7 +65,7 @@ export class SkyBoxMaterial extends Material { } constructor(engine: Engine) { - super(engine, Shader.find("skybox")); + super(engine, Shader.find("Sky/Skybox")); this.renderState.rasterState.cullMode = CullMode.Off; this.renderState.depthState.compareFunction = CompareFunction.LessEqual; diff --git a/packages/core/src/sky/SkyProceduralMaterial.ts b/packages/core/src/sky/SkyProceduralMaterial.ts index 983fc3ca87..08f6b3f3ba 100644 --- a/packages/core/src/sky/SkyProceduralMaterial.ts +++ b/packages/core/src/sky/SkyProceduralMaterial.ts @@ -131,7 +131,7 @@ export class SkyProceduralMaterial extends Material { * @param engine - Engine to which the material belongs */ constructor(engine: Engine) { - super(engine, Shader.find("SkyProcedural")); + super(engine, Shader.find("Sky/SkyProcedural")); this.sunMode = SunMode.HighQuality; this.sunSize = 0.04; this.sunSizeConvergence = 5; diff --git a/packages/core/src/trail/TrailMaterial.ts b/packages/core/src/trail/TrailMaterial.ts index 001c4f3c07..87b9b4e169 100644 --- a/packages/core/src/trail/TrailMaterial.ts +++ b/packages/core/src/trail/TrailMaterial.ts @@ -11,7 +11,7 @@ export class TrailMaterial extends EffectMaterial { * @param engine - Engine to which the material belongs */ constructor(engine: Engine) { - super(engine, Shader.find("trail")); + super(engine, Shader.find("2D/Trail")); } /** diff --git a/packages/design/src/shader-lab/IShaderLab.ts b/packages/design/src/shader-lab/IShaderLab.ts index b14e4516a7..13bb381fb4 100644 --- a/packages/design/src/shader-lab/IShaderLab.ts +++ b/packages/design/src/shader-lab/IShaderLab.ts @@ -15,18 +15,16 @@ export interface IShaderLab { /** * @internal * Parse shader pass source code. - * @param basePathForIncludeKey the base path to resolve the relative path of `#include` directive. Must follow the specifications of [URL.origin](https://developer.mozilla.org/en-US/docs/Web/API/URL/origin), like: `shaders://root/` */ _parseShaderPass( shaderPassSource: string, vertexEntry: string, fragmentEntry: string, - backend: any, - basePathForIncludeKey: string + backend: any ): IShaderProgramSource; /** * @internal */ - _precompile(sourceCode: string, platformTarget: any, basePath: string): IPrecompiledShader; + _precompile(sourceCode: string, platformTarget: any): IPrecompiledShader; } diff --git a/packages/loader/src/ShaderChunkLoader.ts b/packages/loader/src/ShaderChunkLoader.ts deleted file mode 100644 index ede33d9952..0000000000 --- a/packages/loader/src/ShaderChunkLoader.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { - AssetPromise, - LoadItem, - Loader, - ResourceManager, - ShaderFactory, - resourceLoader, - // @ts-ignore - ShaderLib, - Utils -} from "@galacean/engine-core"; - -@resourceLoader("ShaderChunk", ["glsl"]) -export class ShaderChunkLoader extends Loader { - private static _shaderIncludeRegex = /#include\s+"([./][^\\"]+)"/gm; - - /** - * @internal - */ - static _loadChunksInCode(code: string, basePath: string, resourceManager: ResourceManager): Promise { - const shaderChunkPaths = new Array(); - const matches = code.matchAll(ShaderChunkLoader._shaderIncludeRegex); - for (const match of matches) { - const chunkPath = Utils.resolveAbsoluteUrl(basePath, match[1]); - if (!ShaderLib[chunkPath.substring(1)]) { - shaderChunkPaths.push(chunkPath); - } - } - - return Promise.all( - shaderChunkPaths.map((chunkPath) => { - // @ts-ignore - return resourceManager.load({ - type: "ShaderChunk", - url: chunkPath - }); - }) - ); - } - - load(item: LoadItem, resourceManager: ResourceManager): AssetPromise { - const { url } = item; - - // @ts-ignore - return resourceManager._request(url, { ...item, type: "text" }).then((code) => { - ShaderFactory.registerInclude(url.substring(1), code); - - return ShaderChunkLoader._loadChunksInCode(code, url, resourceManager); - }); - } -} diff --git a/packages/loader/src/ShaderLoader.ts b/packages/loader/src/ShaderLoader.ts index 6a56cae6e0..bc09bb1179 100644 --- a/packages/loader/src/ShaderLoader.ts +++ b/packages/loader/src/ShaderLoader.ts @@ -7,14 +7,13 @@ import { Shader, resourceLoader } from "@galacean/engine-core"; -import { ShaderChunkLoader } from "./ShaderChunkLoader"; @resourceLoader(AssetType.Shader, ["shader"]) class ShaderLoader extends Loader { private static _builtinRegex = /^\s*\/\/\s*@builtin\s+(\w+)/; load(item: LoadItem, resourceManager: ResourceManager): AssetPromise { - const { url } = item; + const url = item.url!; if (url.endsWith(".gsp")) { // @ts-ignore @@ -31,10 +30,7 @@ class ShaderLoader extends Loader { return Shader.find(builtinShader); } - return ShaderChunkLoader._loadChunksInCode(code, url, resourceManager).then(() => { - const shader = Shader.create(code, undefined, url); - return shader; - }); + return Shader.create(code); }); } diff --git a/packages/loader/src/index.ts b/packages/loader/src/index.ts index 22ec3c1d2c..c7b1477415 100644 --- a/packages/loader/src/index.ts +++ b/packages/loader/src/index.ts @@ -20,7 +20,6 @@ import "./TextureLoader"; import "./AudioLoader"; import "./ktx2/KTX2Loader"; import "./ShaderLoader"; -import "./ShaderChunkLoader"; import "./PhysicsMaterialLoader"; import "./RenderTargetLoader"; diff --git a/packages/shader-lab/src/Preprocessor.ts b/packages/shader-lab/src/Preprocessor.ts index 17e907da73..36cd3fac94 100644 --- a/packages/shader-lab/src/Preprocessor.ts +++ b/packages/shader-lab/src/Preprocessor.ts @@ -1,4 +1,4 @@ -import { Logger, ShaderPass } from "@galacean/engine"; +import { Logger } from "@galacean/engine"; /** @ts-ignore */ import { ShaderLib } from "@galacean/engine"; @@ -35,18 +35,11 @@ export class Preprocessor { */ static _repeatIncludeSet = new Set(); - static parse( - source: string, - basePathForIncludeKey: string, - outMacroDefineList: MacroDefineList, - parseMacro = true - ): string { + static parse(source: string, outMacroDefineList: MacroDefineList, parseMacro = true): string { if (parseMacro) { this._parseMacroDefines(source, outMacroDefineList); } - return source.replace(this._includeReg, (_, includeName) => - this._replace(includeName, basePathForIncludeKey, outMacroDefineList) - ); + return source.replace(this._includeReg, (_, includeName) => this._replace(includeName, outMacroDefineList)); } static getReferenceSymbolNames(macroDefineList: MacroDefineList, macroName: string, out: string[]): void { @@ -151,39 +144,27 @@ export class Preprocessor { } } - private static _replace( - includeName: string, - basePathForIncludeKey: string, - outMacroDefineList: MacroDefineList - ): string { - let path: string; - if (includeName[0] === ".") { - // @ts-ignore - path = new URL(includeName, basePathForIncludeKey).href.substring(ShaderPass._shaderRootPath.length); - } else { - path = includeName; - } - - const chunk = (ShaderLib as any)[path]; + private static _replace(includeName: string, outMacroDefineList: MacroDefineList): string { + const chunk = (ShaderLib as any)[includeName]; if (!chunk) { - Logger.error(`Shader slice "${path}" not founded.`); + Logger.error(`Shader slice "${includeName}" not founded.`); return ""; } - if (this._repeatIncludeSet.has(path)) { - Logger.warn(`Shader slice "${path}" is included multiple times.`); + if (this._repeatIncludeSet.has(includeName)) { + Logger.warn(`Shader slice "${includeName}" is included multiple times.`); } - this._repeatIncludeSet.add(path); + this._repeatIncludeSet.add(includeName); - if (this._macroDefineIncludeMap.has(path)) { - this._mergeMacroDefineLists(this._macroDefineIncludeMap.get(path)!, outMacroDefineList); + if (this._macroDefineIncludeMap.has(includeName)) { + this._mergeMacroDefineLists(this._macroDefineIncludeMap.get(includeName)!, outMacroDefineList); } else { const chunkMacroDefineList: MacroDefineList = {}; this._parseMacroDefines(chunk, chunkMacroDefineList); - this._macroDefineIncludeMap.set(path, chunkMacroDefineList); + this._macroDefineIncludeMap.set(includeName, chunkMacroDefineList); this._mergeMacroDefineLists(chunkMacroDefineList, outMacroDefineList); } - return this.parse(chunk, basePathForIncludeKey, outMacroDefineList, false); + return this.parse(chunk, outMacroDefineList, false); } } diff --git a/packages/shader-lab/src/ShaderLab.ts b/packages/shader-lab/src/ShaderLab.ts index e3745c2db6..f245b57912 100644 --- a/packages/shader-lab/src/ShaderLab.ts +++ b/packages/shader-lab/src/ShaderLab.ts @@ -52,13 +52,12 @@ export class ShaderLab implements IShaderLab { source: string, vertexEntry: string, fragmentEntry: string, - backend: ShaderLanguage, - basePathForIncludeKey: string + backend: ShaderLanguage ): IShaderProgramSource | undefined { const totalStartTime = performance.now(); const macroDefineList = {}; Preprocessor._repeatIncludeSet.clear(); - const noIncludeContent = Preprocessor.parse(source, basePathForIncludeKey, macroDefineList); + const noIncludeContent = Preprocessor.parse(source, macroDefineList); Logger.info(`[Task - Pre processor] cost time ${performance.now() - totalStartTime}ms`); const lexer = new Lexer(noIncludeContent, macroDefineList); @@ -99,7 +98,7 @@ export class ShaderLab implements IShaderLab { return ret; } - _precompile(sourceCode: string, platformTarget: ShaderLanguage, basePath: string): IPrecompiledShader { + _precompile(sourceCode: string, platformTarget: ShaderLanguage): IPrecompiledShader { const shaderSource = this._parseShaderSource(sourceCode); const subShaders = shaderSource.subShaders.map((sub) => ({ @@ -119,8 +118,7 @@ export class ShaderLab implements IShaderLab { pass.contents, pass.vertexEntry, pass.fragmentEntry, - platformTarget, - basePath + platformTarget ); if (!programSource) { diff --git a/packages/shader/package.json b/packages/shader/package.json index e15a461b3f..9143424847 100644 --- a/packages/shader/package.json +++ b/packages/shader/package.json @@ -18,19 +18,10 @@ "b:types": "tsc" }, "umd": { - "name": "Galacean.ShaderFragment", - "globals": { - "@galacean/engine": "Galacean" - } + "name": "Galacean.ShaderFragment" }, "files": [ "dist/**/*", "types/**/*" - ], - "devDependencies": { - "@galacean/engine": "workspace:*" - }, - "peerDependencies": { - "@galacean/engine": "workspace:*" - } + ] } diff --git a/packages/core/src/lighting/ambientOcclusion/shaders/Blur/BilateralBlur.glsl b/packages/shader/src/ShaderLibrary/AO/BilateralBlur.glsl similarity index 61% rename from packages/core/src/lighting/ambientOcclusion/shaders/Blur/BilateralBlur.glsl rename to packages/shader/src/ShaderLibrary/AO/BilateralBlur.glsl index e346b77dfc..45c1b28b59 100644 --- a/packages/core/src/lighting/ambientOcclusion/shaders/Blur/BilateralBlur.glsl +++ b/packages/shader/src/ShaderLibrary/AO/BilateralBlur.glsl @@ -1,9 +1,12 @@ -#include +#ifndef BILATERAL_BLUR_INCLUDED +#define BILATERAL_BLUR_INCLUDED + +#include "Common/Common.glsl" + +sampler2D renderer_BlitTexture; +vec4 renderer_SourceScaleOffset; +float material_farPlaneOverEdgeDistance; -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; -uniform vec4 renderer_SourceScaleOffset; -uniform float material_farPlaneOverEdgeDistance; #if SSAO_QUALITY == 0 #define BLUR_SAMPLE_COUNT 3 #elif SSAO_QUALITY == 1 @@ -12,7 +15,7 @@ uniform float material_farPlaneOverEdgeDistance; #define BLUR_SAMPLE_COUNT 12 #endif -uniform float material_kernel[12]; // Sample weights for bilateral blur +float material_kernel[12]; float bilateralWeight(float depth, float sampleDepth) { float diff = (sampleDepth - depth) * material_farPlaneOverEdgeDistance; @@ -20,42 +23,36 @@ float bilateralWeight(float depth, float sampleDepth) { } highp float unpack(highp vec2 depth) { - // depth here only has 8-bits of precision, but the unpacked depth is highp - // this is equivalent to (x8 * 256 + y8) / 65535, which gives a value between 0 and 1 return (depth.x * (256.0 / 257.0) + depth.y * (1.0 / 257.0)); } void tap(const sampler2D saoTexture, inout float sum, inout float totalWeight, float weight, float depth, vec2 position) { vec4 data = texture2D(saoTexture, position); - // bilateral sample - float bilateral = weight * bilateralWeight(depth, unpack(data.gb)); + float bilateral = weight * bilateralWeight(depth, unpack(data.gb)); sum += data.r * bilateral; totalWeight += bilateral; } -void main(){ - mediump vec4 data = texture2D(renderer_BlitTexture, v_uv); +void frag(Varyings v) { + mediump vec4 data = texture2D(renderer_BlitTexture, v.v_uv); float depth = unpack(data.gb); - // Weight of the center pixel from the Gaussian kernel (typically 1.0) float totalWeight = material_kernel[0]; float sum = data.r * totalWeight; - + vec2 offset = renderer_SourceScaleOffset.zw; for (int i = 1; i < BLUR_SAMPLE_COUNT; i++) { float weight = material_kernel[i]; - tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v_uv + offset); - tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v_uv - offset); + tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v.v_uv + offset); + tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v.v_uv - offset); offset += renderer_SourceScaleOffset.zw; } float ao = sum * (1.0 / totalWeight); - // simple dithering helps a lot (assumes 8 bits target) - // this is most useful with high quality/large blurs ao += ((interleavedGradientNoise(gl_FragCoord.xy) - 0.5) / 255.0); gl_FragColor = vec4(ao, data.gb, 1.0); - } +#endif diff --git a/packages/core/src/lighting/ambientOcclusion/shaders/ScalableAmbientOcclusion.glsl b/packages/shader/src/ShaderLibrary/AO/ScalableAmbientOcclusion.glsl similarity index 62% rename from packages/core/src/lighting/ambientOcclusion/shaders/ScalableAmbientOcclusion.glsl rename to packages/shader/src/ShaderLibrary/AO/ScalableAmbientOcclusion.glsl index b12655ff2a..e7a6125d72 100644 --- a/packages/core/src/lighting/ambientOcclusion/shaders/ScalableAmbientOcclusion.glsl +++ b/packages/shader/src/ShaderLibrary/AO/ScalableAmbientOcclusion.glsl @@ -1,13 +1,15 @@ +#ifndef SCALABLE_AMBIENT_OCCLUSION_INCLUDED +#define SCALABLE_AMBIENT_OCCLUSION_INCLUDED + // Ambient Occlusion, largely inspired from: // "The Alchemy Screen-Space Ambient Obscurance Algorithm" by Morgan McGuire // "Scalable Ambient Obscurance" by Morgan McGuire, Michael Mara and David Luebke // https://research.nvidia.com/sites/default/files/pubs/2012-06_Scalable-Ambient-Obscurance/McGuire12SAO.pdf -#include +#include "Common/Common.glsl" -varying vec2 v_uv; -uniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height -uniform highp sampler2D renderer_BlitTexture; // Camera_DepthTexture +vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height +highp sampler2D renderer_BlitTexture; // Camera_DepthTexture // float inc = (1.0f / (SAMPLE_COUNT - 0.5f)) * SPIRAL_TURNS * 2.0 * PI // const vec2 angleIncCosSin = vec2(cos(inc), sin(inc)) @@ -25,14 +27,14 @@ uniform highp sampler2D renderer_BlitTexture; // Camera_DepthTexture const vec2 angleIncCosSin = vec2(-0.966846, 0.255311); #endif -uniform float material_invRadiusSquared; // Inverse of the squared radius -uniform float material_minHorizonAngleSineSquared; // Minimum horizon angle sine squared -uniform float material_intensity; // Intensity of the ambient occlusion -uniform float material_projectionScaleRadius; -uniform float material_bias; // Bias to avoid self-occlusion -uniform float material_peak2; // Peak value to avoid singularities -uniform float material_power; // Exponent to convert occlusion to visibility -uniform vec2 material_invProjScaleXY; //invProjection[0][0] * 2, invProjection[1][1] * 2 +float material_invRadiusSquared; +float material_minHorizonAngleSineSquared; +float material_intensity; +float material_projectionScaleRadius; +float material_bias; +float material_peak2; +float material_power; +vec2 material_invProjScaleXY; vec3 computeViewSpacePosition(vec2 uv, float linearDepth, vec2 invProjScaleXY) { @@ -47,9 +49,6 @@ float depthToViewZ(float depth) { return -remapDepthBufferEyeDepth(depth); } -// reconstructing normal from depth buffer -// https://atyuwen.github.io/posts/normal-reconstruction -// https://wickedengine.net/2019/09/22/improved-normal-reconstruction-from-depth/ vec3 computeViewSpaceNormal(vec2 uv, highp sampler2D depthTexture, float depth, vec3 viewPos, vec2 texel, vec2 invProjScaleXY) { vec3 normal = vec3(0.0); #if SSAO_QUALITY == 0 || SSAO_QUALITY == 1 @@ -70,28 +69,25 @@ vec3 computeViewSpaceNormal(vec2 uv, highp sampler2D depthTexture, float depth, #elif SSAO_QUALITY == 2 vec2 dx = vec2(texel.x, 0.0); vec2 dy = vec2(0.0, texel.y); - + vec4 H; - H.x = texture2D(depthTexture, uv - dx).r; // left - H.y = texture2D(depthTexture, uv + dx).r; // right - H.z = texture2D(depthTexture, uv - dx * 2.0).r; // left2 - H.w = texture2D(depthTexture, uv + dx * 2.0).r; // right2 - - // Calculate horizontal edge weights + H.x = texture2D(depthTexture, uv - dx).r; + H.y = texture2D(depthTexture, uv + dx).r; + H.z = texture2D(depthTexture, uv - dx * 2.0).r; + H.w = texture2D(depthTexture, uv + dx * 2.0).r; + vec2 horizontalEdgeWeights = abs((2.0 * H.xy - H.zw) - depth); vec3 pos_l = computeViewSpacePosition(uv - dx, depthToViewZ(H.x), invProjScaleXY); vec3 pos_r = computeViewSpacePosition(uv + dx, depthToViewZ(H.y), invProjScaleXY); vec3 dpdx = (horizontalEdgeWeights.x < horizontalEdgeWeights.y) ? (viewPos - pos_l) : (pos_r - viewPos); - // Sample depths for vertical edge detection vec4 V; - V.x = texture2D(depthTexture, uv - dy).r; // down - V.y = texture2D(depthTexture, uv + dy).r; // up - V.z = texture2D(depthTexture, uv - dy * 2.0).r; // down2 - V.w = texture2D(depthTexture, uv + dy * 2.0).r; // up2 + V.x = texture2D(depthTexture, uv - dy).r; + V.y = texture2D(depthTexture, uv + dy).r; + V.z = texture2D(depthTexture, uv - dy * 2.0).r; + V.w = texture2D(depthTexture, uv + dy * 2.0).r; - // Calculate vertical edge weights vec2 verticalEdgeWeights = abs((2.0 * V.xy - V.zw) - depth); vec3 pos_d = computeViewSpacePosition(uv - dy, depthToViewZ(V.x), invProjScaleXY); vec3 pos_u = computeViewSpacePosition(uv + dy, depthToViewZ(V.y), invProjScaleXY); @@ -99,7 +95,6 @@ vec3 computeViewSpaceNormal(vec2 uv, highp sampler2D depthTexture, float depth, normal = normalize(cross(dpdx, dpdy)); #endif return normal; - } vec3 tapLocation(float i, const float noise) { @@ -128,33 +123,20 @@ void computeAmbientOcclusionSAO(inout float occlusion, float i, float ssDiskRadi vec2 tapPosition, float noise) { vec3 tap = tapLocationFast(i, tapPosition, noise); - - float ssRadius = max(1.0, tap.z * ssDiskRadius); // at least 1 pixel screen-space radius - + float ssRadius = max(1.0, tap.z * ssDiskRadius); vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * renderer_texelSize.xy; float occlusionDepth = texture2D(renderer_BlitTexture, uvSamplePos).r; float linearOcclusionDepth = depthToViewZ(occlusionDepth); - // “p” is the position after spiral sampling vec3 p = computeViewSpacePosition(uvSamplePos, linearOcclusionDepth, material_invProjScaleXY); - // now we have the sample, compute AO - vec3 v = p - originPosition; // sample vector - float vv = dot(v, v); // squared distance - float vn = dot(v, normal); // distance * cos(v, normal) + vec3 v = p - originPosition; + float vv = dot(v, v); + float vn = dot(v, normal); - // discard samples that are outside of the radius, preventing distant geometry to - // cast shadows -- there are many functions that work and choosing one is an artistic - // decision. float weight = pow(max(0.0, 1.0 - vv * material_invRadiusSquared), 2.0); - - // discard samples that are too close to the horizon to reduce shadows cast by geometry - // not sufficently tessellated. The goal is to discard samples that form an angle 'beta' - // smaller than 'epsilon' with the horizon. We already have dot(v,n) which is equal to the - // sin(beta) * |v|. So the test simplifies to vn^2 < vv * sin(epsilon)^2. weight *= step(vv * material_minHorizonAngleSineSquared, vn * vn); - // Calculate the contribution of a single sampling point to Ambient Occlusion float sampleOcclusion = max(0.0, vn + (originPosition.z * material_bias)) / (vv + material_peak2); occlusion += weight * sampleOcclusion; } @@ -164,11 +146,8 @@ void scalableAmbientObscurance(vec2 uv, vec3 origin, vec3 normal, out float obsc vec2 tapPosition = startPosition(noise); mat2 angleStep = tapAngleStep(); - // Choose the screen-space sample radius - // proportional to the projected area of the sphere float ssDiskRadius = -(material_projectionScaleRadius / origin.z); - // Accumulate the occlusion amount of all sampling points obscurance = 0.0; for (float i = 0.0; i < SAMPLE_COUNT; i += 1.0) { computeAmbientOcclusionSAO(obscurance, i, ssDiskRadius, uv, origin, normal, tapPosition, noise); @@ -186,22 +165,19 @@ vec2 pack(highp float normalizedDepth) { } -void main(){ - float depth = texture2D(renderer_BlitTexture, v_uv).r; +void frag(Varyings v) { + float depth = texture2D(renderer_BlitTexture, v.v_uv).r; float z = depthToViewZ(depth); - // Reconstruct view space position from depth - vec3 positionVS = computeViewSpacePosition(v_uv, z, material_invProjScaleXY); - - // Compute normal - vec3 normal = computeViewSpaceNormal(v_uv, renderer_BlitTexture, depth, positionVS, renderer_texelSize.xy, material_invProjScaleXY); + vec3 positionVS = computeViewSpacePosition(v.v_uv, z, material_invProjScaleXY); + vec3 normal = computeViewSpaceNormal(v.v_uv, renderer_BlitTexture, depth, positionVS, renderer_texelSize.xy, material_invProjScaleXY); float occlusion = 0.0; - scalableAmbientObscurance(v_uv, positionVS, normal, occlusion); + scalableAmbientObscurance(v.v_uv, positionVS, normal, occlusion); - // Occlusion to visibility float aoVisibility = pow(clamp(1.0 - occlusion, 0.0, 1.0), material_power); gl_FragColor = vec4(aoVisibility, pack(-positionVS.z/camera_ProjectionParams.z), 1.0); } +#endif diff --git a/packages/shader/src/ShaderLibrary/BlinnPhong/ForwardPassBlinnPhong.glsl b/packages/shader/src/ShaderLibrary/BlinnPhong/ForwardPassBlinnPhong.glsl new file mode 100644 index 0000000000..d9a0fe6d1c --- /dev/null +++ b/packages/shader/src/ShaderLibrary/BlinnPhong/ForwardPassBlinnPhong.glsl @@ -0,0 +1,254 @@ +#ifndef FORWARD_PASS_BLINNPHONG_INCLUDED +#define FORWARD_PASS_BLINNPHONG_INCLUDED + +#include "Common/Common.glsl" +#include "Common/Fog.glsl" +#include "Common/Transform.glsl" +#include "Skin/Skin.glsl" +#include "Skin/BlendShape.glsl" +#include "Shadow/Shadow.glsl" +#include "Common/MobileBlinnPhong.glsl" +#include "Common/ViewDirection.glsl" + +vec4 material_TilingOffset; + +struct Attributes { + vec3 POSITION; + + #ifdef RENDERER_HAS_BLENDSHAPE + #ifndef RENDERER_BLENDSHAPE_USE_TEXTURE + vec3 POSITION_BS0; + vec3 POSITION_BS1; + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) && defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + #else + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) || defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 POSITION_BS2; + vec3 POSITION_BS3; + #ifdef RENDERER_BLENDSHAPE_HAS_NORMAL + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 NORMAL_BS2; + vec3 NORMAL_BS3; + #endif + #ifdef RENDERER_BLENDSHAPE_HAS_TANGENT + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + vec3 TANGENT_BS2; + vec3 TANGENT_BS3; + #endif + #else + vec3 POSITION_BS2; + vec3 POSITION_BS3; + vec3 POSITION_BS4; + vec3 POSITION_BS5; + vec3 POSITION_BS6; + vec3 POSITION_BS7; + #endif + #endif + #endif + #endif + + #ifdef RENDERER_HAS_UV + vec2 TEXCOORD_0; + #endif + + #ifdef RENDERER_HAS_SKIN + vec4 JOINTS_0; + vec4 WEIGHTS_0; + #endif + + #ifdef RENDERER_ENABLE_VERTEXCOLOR + vec4 COLOR_0; + #endif + + #ifdef RENDERER_HAS_NORMAL + vec3 NORMAL; + #endif + + #ifdef RENDERER_HAS_TANGENT + vec4 TANGENT; + #endif +}; + +struct Varyings { + vec2 v_uv; + + #ifdef RENDERER_ENABLE_VERTEXCOLOR + vec4 v_color; + #endif + + vec3 v_pos; + + #if SCENE_FOG_MODE != 0 + vec3 v_positionVS; + #endif + + #ifdef RENDERER_HAS_NORMAL + vec3 v_normalWS; + #ifdef RENDERER_HAS_TANGENT + vec3 v_tangentWS; + vec3 v_bitangentWS; + #endif + #endif + + #if defined(NEED_CALCULATE_SHADOWS) && (SCENE_SHADOW_CASCADED_COUNT == 1) + vec3 v_shadowCoord; + #endif +}; + + +Varyings BlinnPhongVertex(Attributes attr) { + Varyings v; + + vec4 position = vec4(attr.POSITION, 1.0); + + #ifdef RENDERER_HAS_NORMAL + vec3 normal = attr.NORMAL; + #ifdef RENDERER_HAS_TANGENT + vec4 tangent = attr.TANGENT; + #endif + #endif + + // Blend shape + #ifdef RENDERER_HAS_BLENDSHAPE + calculateBlendShape(attr, position + #ifdef RENDERER_HAS_NORMAL + , normal + #ifdef RENDERER_HAS_TANGENT + , tangent + #endif + #endif + ); + #endif + + // Skinning + #ifdef RENDERER_HAS_SKIN + mat4 skinMatrix = getSkinMatrix(attr); + position = skinMatrix * position; + #ifdef RENDERER_HAS_NORMAL + normal = (skinMatrix * vec4(normal, 0.0)).xyz; + #ifdef RENDERER_HAS_TANGENT + tangent.xyz = (skinMatrix * vec4(tangent.xyz, 0.0)).xyz; + #endif + #endif + #endif + + // UV + #ifdef RENDERER_HAS_UV + v.v_uv = attr.TEXCOORD_0; + #else + v.v_uv = vec2(0.0); + #endif + #ifdef MATERIAL_NEED_TILING_OFFSET + v.v_uv = v.v_uv * material_TilingOffset.xy + material_TilingOffset.zw; + #endif + + // Vertex color + #ifdef RENDERER_ENABLE_VERTEXCOLOR + v.v_color = attr.COLOR_0; + #endif + + // Normal + #ifdef RENDERER_HAS_NORMAL + v.v_normalWS = normalize((renderer_NormalMat * vec4(normal, 0.0)).xyz); + #ifdef RENDERER_HAS_TANGENT + vec3 tangentWS = normalize((renderer_ModelMat * vec4(tangent.xyz, 0.0)).xyz); + v.v_tangentWS = tangentWS; + v.v_bitangentWS = cross(v.v_normalWS, tangentWS) * tangent.w; + #endif + #endif + + // World position + vec4 worldPos = renderer_ModelMat * position; + v.v_pos = worldPos.xyz / worldPos.w; + + // Clip position + gl_Position = renderer_MVPMat * position; + + // Shadow + #if defined(NEED_CALCULATE_SHADOWS) && (SCENE_SHADOW_CASCADED_COUNT == 1) + v.v_shadowCoord = getShadowCoord(v.v_pos); + #endif + + // Fog + #if SCENE_FOG_MODE != 0 + v.v_positionVS = (renderer_MVMat * position).xyz; + #endif + + return v; +} + + +void BlinnPhongFragment(Varyings v) { + vec4 ambient, emission, diffuse, specular; + initBlinnPhongMaterial(v.v_uv, ambient, emission, diffuse, specular); + + // Apply vertex color + #ifdef RENDERER_ENABLE_VERTEXCOLOR + diffuse *= v.v_color; + #endif + + // Normal + vec3 N; + #ifdef RENDERER_HAS_NORMAL + N = v.v_normalWS; + #ifdef MATERIAL_HAS_NORMALTEXTURE + #ifdef RENDERER_HAS_TANGENT + mat3 tbn = mat3(v.v_tangentWS, v.v_bitangentWS, v.v_normalWS); + #else + mat3 tbn = getTBNByDerivatives(v.v_uv, N, v.v_pos, gl_FrontFacing); + #endif + N = getNormalByNormalTexture(tbn, material_NormalTexture, material_NormalIntensity, v.v_uv, gl_FrontFacing); + #else + N *= float(gl_FrontFacing) * 2.0 - 1.0; + #endif + #else + N = vec3(0.0, 0.0, 1.0); + #endif + + // View direction + vec3 V = getViewDirection(camera_Position, camera_Forward, v.v_pos); + + // Shadow + float shadowAttenuation = 1.0; + #if defined(SCENE_DIRECT_LIGHT_COUNT) && defined(NEED_CALCULATE_SHADOWS) + #if SCENE_SHADOW_CASCADED_COUNT == 1 + vec3 shadowCoord = v.v_shadowCoord; + #else + vec3 shadowCoord = getShadowCoord(v.v_pos); + #endif + shadowAttenuation *= sampleShadowMap(v.v_pos, shadowCoord); + #endif + + // Lighting + calculateBlinnPhongLighting(N, V, v.v_pos, shadowAttenuation, diffuse, specular); + + // Alpha cutoff + #ifdef MATERIAL_IS_ALPHA_CUTOFF + if (diffuse.a < material_AlphaCutoff) { + discard; + } + #endif + + vec4 color = emission + ambient + diffuse + specular; + + #ifdef MATERIAL_IS_TRANSPARENT + color.a = diffuse.a; + #else + color.a = 1.0; + #endif + + // Fog + #if SCENE_FOG_MODE != 0 + color = fog(color, v.v_positionVS); + #endif + + gl_FragColor = color; +} + + +#endif diff --git a/packages/shader/src/ShaderLibrary/Common/BlitVertex.glsl b/packages/shader/src/ShaderLibrary/Common/BlitVertex.glsl new file mode 100644 index 0000000000..3f2effb969 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/BlitVertex.glsl @@ -0,0 +1,19 @@ +#ifndef BLIT_VERTEX_INCLUDED +#define BLIT_VERTEX_INCLUDED + +struct Attributes { + vec4 POSITION_UV; +}; + +struct Varyings { + vec2 v_uv; +}; + +Varyings vert(Attributes attr) { + Varyings v; + gl_Position = vec4(attr.POSITION_UV.xy, 0.0, 1.0); + v.v_uv = attr.POSITION_UV.zw; + return v; +} + +#endif diff --git a/packages/shader/src/ShaderLibrary/Common/Color.glsl b/packages/shader/src/ShaderLibrary/Common/Color.glsl new file mode 100644 index 0000000000..eed09e5c58 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/Color.glsl @@ -0,0 +1,16 @@ +#ifndef COLOR_INCLUDED +#define COLOR_INCLUDED + +#ifdef RENDERER_ENABLE_VERTEXCOLOR + varying vec4 v_color; +#endif + +// Vertex: assign vertex color +// Requires COLOR_0 attribute +#ifdef RENDERER_ENABLE_VERTEXCOLOR + void initVertexColor(vec4 vertexColor, inout vec4 vColor) { + vColor = vertexColor; + } +#endif + +#endif diff --git a/packages/shader/src/shaders/Common.glsl b/packages/shader/src/ShaderLibrary/Common/Common.glsl similarity index 99% rename from packages/shader/src/shaders/Common.glsl rename to packages/shader/src/ShaderLibrary/Common/Common.glsl index 6dc50576b5..678d1a62b0 100644 --- a/packages/shader/src/shaders/Common.glsl +++ b/packages/shader/src/ShaderLibrary/Common/Common.glsl @@ -64,6 +64,7 @@ vec4 outputSRGBCorrection(vec4 linearIn){ vec4 camera_DepthBufferParams; +vec4 camera_ProjectionParams; float remapDepthBufferLinear01(float depth){ return 1.0 / (camera_DepthBufferParams.x * depth + camera_DepthBufferParams.y); diff --git a/packages/shader/src/shaders/Fog.glsl b/packages/shader/src/ShaderLibrary/Common/Fog.glsl similarity index 100% rename from packages/shader/src/shaders/Fog.glsl rename to packages/shader/src/ShaderLibrary/Common/Fog.glsl diff --git a/packages/shader/src/shaders/Light.glsl b/packages/shader/src/ShaderLibrary/Common/Light.glsl similarity index 100% rename from packages/shader/src/shaders/Light.glsl rename to packages/shader/src/ShaderLibrary/Common/Light.glsl diff --git a/packages/shader/src/ShaderLibrary/Common/MobileBlinnPhong.glsl b/packages/shader/src/ShaderLibrary/Common/MobileBlinnPhong.glsl new file mode 100644 index 0000000000..2ea72162fa --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/MobileBlinnPhong.glsl @@ -0,0 +1,142 @@ +#ifndef MOBILE_BLINNPHONG_INCLUDED +#define MOBILE_BLINNPHONG_INCLUDED + +#include "Common/Common.glsl" +#include "Common/Light.glsl" +#include "Common/Normal.glsl" + +// Material uniforms +vec4 material_EmissiveColor; +vec4 material_BaseColor; +vec4 material_SpecularColor; +float material_Shininess; +float material_NormalIntensity; +float material_AlphaCutoff; + +#ifdef MATERIAL_HAS_EMISSIVETEXTURE + sampler2D material_EmissiveTexture; +#endif + +#ifdef MATERIAL_HAS_BASETEXTURE + sampler2D material_BaseTexture; +#endif + +#ifdef MATERIAL_HAS_SPECULAR_TEXTURE + sampler2D material_SpecularTexture; +#endif + +#ifdef MATERIAL_HAS_NORMALTEXTURE + sampler2D material_NormalTexture; +#endif + +// Initialize material colors from textures +// Note: vertex color should be applied by the caller after this function +void initBlinnPhongMaterial(vec2 uv, out vec4 ambient, out vec4 emission, out vec4 diffuse, out vec4 specular) { + ambient = vec4(0.0); + emission = material_EmissiveColor; + diffuse = material_BaseColor; + specular = material_SpecularColor; + + #ifdef MATERIAL_HAS_EMISSIVETEXTURE + emission *= texture2DSRGB(material_EmissiveTexture, uv); + #endif + + #ifdef MATERIAL_HAS_BASETEXTURE + diffuse *= texture2DSRGB(material_BaseTexture, uv); + #endif + + #ifdef MATERIAL_HAS_SPECULAR_TEXTURE + specular *= texture2DSRGB(material_SpecularTexture, uv); + #endif + + ambient = vec4(scene_EnvMapLight.diffuse * scene_EnvMapLight.diffuseIntensity, 1.0) * diffuse; +} + +// Calculate Blinn-Phong lighting +// shadowAttenuation: pre-computed shadow factor (1.0 = no shadow) +void calculateBlinnPhongLighting( + vec3 N, vec3 V, vec3 worldPos, + float shadowAttenuation, + inout vec4 diffuse, inout vec4 specular +) { + vec3 lightDiffuse = vec3(0.0); + vec3 lightSpecular = vec3(0.0); + + #ifdef SCENE_DIRECT_LIGHT_COUNT + DirectLight directionalLight; + for (int i = 0; i < SCENE_DIRECT_LIGHT_COUNT; i++) { + if (!isRendererCulledByLight(renderer_Layer.xy, scene_DirectLightCullingMask[i])) { + directionalLight.color = scene_DirectLightColor[i]; + #ifdef SCENE_IS_CALCULATE_SHADOWS + if (i == 0) { + directionalLight.color *= shadowAttenuation; + } + #endif + directionalLight.direction = scene_DirectLightDirection[i]; + + float d = max(dot(N, -directionalLight.direction), 0.0); + lightDiffuse += directionalLight.color * d; + + vec3 halfDir = normalize(V - directionalLight.direction); + float s = pow(clamp(dot(N, halfDir), 0.0, 1.0), material_Shininess); + lightSpecular += directionalLight.color * s; + } + } + #endif + + #ifdef SCENE_POINT_LIGHT_COUNT + PointLight pointLight; + for (int i = 0; i < SCENE_POINT_LIGHT_COUNT; i++) { + if (!isRendererCulledByLight(renderer_Layer.xy, scene_PointLightCullingMask[i])) { + pointLight.color = scene_PointLightColor[i]; + pointLight.position = scene_PointLightPosition[i]; + pointLight.distance = scene_PointLightDistance[i]; + + vec3 direction = worldPos - pointLight.position; + float dist = length(direction); + direction /= dist; + float decay = clamp(1.0 - pow(dist / pointLight.distance, 4.0), 0.0, 1.0); + + float d = max(dot(N, -direction), 0.0) * decay; + lightDiffuse += pointLight.color * d; + + vec3 halfDir = normalize(V - direction); + float s = pow(clamp(dot(N, halfDir), 0.0, 1.0), material_Shininess) * decay; + lightSpecular += pointLight.color * s; + } + } + #endif + + #ifdef SCENE_SPOT_LIGHT_COUNT + SpotLight spotLight; + for (int i = 0; i < SCENE_SPOT_LIGHT_COUNT; i++) { + if (!isRendererCulledByLight(renderer_Layer.xy, scene_SpotLightCullingMask[i])) { + spotLight.color = scene_SpotLightColor[i]; + spotLight.position = scene_SpotLightPosition[i]; + spotLight.direction = scene_SpotLightDirection[i]; + spotLight.distance = scene_SpotLightDistance[i]; + spotLight.angleCos = scene_SpotLightAngleCos[i]; + spotLight.penumbraCos = scene_SpotLightPenumbraCos[i]; + + vec3 direction = spotLight.position - worldPos; + float lightDistance = length(direction); + direction /= lightDistance; + float angleCos = dot(direction, -spotLight.direction); + float decay = clamp(1.0 - pow(lightDistance / spotLight.distance, 4.0), 0.0, 1.0); + float spotEffect = smoothstep(spotLight.penumbraCos, spotLight.angleCos, angleCos); + float decayTotal = decay * spotEffect; + float d = max(dot(N, direction), 0.0) * decayTotal; + lightDiffuse += spotLight.color * d; + + vec3 halfDir = normalize(V + direction); + float s = pow(clamp(dot(N, halfDir), 0.0, 1.0), material_Shininess) * decayTotal; + lightSpecular += spotLight.color * s; + } + } + #endif + + diffuse *= vec4(lightDiffuse, 1.0); + specular *= vec4(lightSpecular, 1.0); +} + +#endif diff --git a/packages/shader/src/shaders/Normal.glsl b/packages/shader/src/ShaderLibrary/Common/Normal.glsl similarity index 100% rename from packages/shader/src/shaders/Normal.glsl rename to packages/shader/src/ShaderLibrary/Common/Normal.glsl diff --git a/packages/shader/src/ShaderLibrary/Common/Position.glsl b/packages/shader/src/ShaderLibrary/Common/Position.glsl new file mode 100644 index 0000000000..4eaeec3429 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/Position.glsl @@ -0,0 +1,12 @@ +#ifndef POSITION_INCLUDED +#define POSITION_INCLUDED + +vec4 initPosition(vec3 vertexPosition) { + return vec4(vertexPosition, 1.0); +} + +void calculateClipPosition(mat4 mvpMat, vec4 position) { + gl_Position = mvpMat * position; +} + +#endif diff --git a/packages/shader/src/ShaderLibrary/Common/PositionClipSpace.glsl b/packages/shader/src/ShaderLibrary/Common/PositionClipSpace.glsl new file mode 100644 index 0000000000..785347e39e --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/PositionClipSpace.glsl @@ -0,0 +1,14 @@ +#ifndef POSITION_CLIP_SPACE_INCLUDED +#define POSITION_CLIP_SPACE_INCLUDED + +#ifdef SCENE_ENABLE_AMBIENT_OCCLUSION + varying vec4 v_PositionCS; +#endif + +void initPositionClipSpace() { + #ifdef SCENE_ENABLE_AMBIENT_OCCLUSION + v_PositionCS = gl_Position; + #endif +} + +#endif diff --git a/packages/shader/src/shaders/Transform.glsl b/packages/shader/src/ShaderLibrary/Common/Transform.glsl similarity index 82% rename from packages/shader/src/shaders/Transform.glsl rename to packages/shader/src/ShaderLibrary/Common/Transform.glsl index b5d1a52a68..472fb4fe2b 100644 --- a/packages/shader/src/shaders/Transform.glsl +++ b/packages/shader/src/ShaderLibrary/Common/Transform.glsl @@ -10,7 +10,6 @@ mat4 renderer_MVPMat; mat4 renderer_NormalMat; vec3 camera_Position; -vec3 camera_Forward; -vec4 camera_ProjectionParams; +vec3 camera_Forward; #endif \ No newline at end of file diff --git a/packages/shader/src/ShaderLibrary/Common/UV.glsl b/packages/shader/src/ShaderLibrary/Common/UV.glsl new file mode 100644 index 0000000000..2fbe632898 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/UV.glsl @@ -0,0 +1,28 @@ +#ifndef UV_INCLUDED +#define UV_INCLUDED + +varying vec2 v_uv; + +#ifdef RENDERER_HAS_UV1 + varying vec2 v_uv1; +#endif + +vec4 material_TilingOffset; + +void initUV(out vec2 uv, out vec2 uv1) { + #ifdef RENDERER_HAS_UV + uv = TEXCOORD_0; + #else + uv = vec2(0.0, 0.0); + #endif + + #ifdef RENDERER_HAS_UV1 + uv1 = TEXCOORD_1; + #endif + + #ifdef MATERIAL_NEED_TILING_OFFSET + uv = uv * material_TilingOffset.xy + material_TilingOffset.zw; + #endif +} + +#endif diff --git a/packages/shader/src/ShaderLibrary/Common/ViewDirection.glsl b/packages/shader/src/ShaderLibrary/Common/ViewDirection.glsl new file mode 100644 index 0000000000..c8132a5ace --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/ViewDirection.glsl @@ -0,0 +1,12 @@ +#ifndef VIEW_DIRECTION_INCLUDED +#define VIEW_DIRECTION_INCLUDED + +vec3 getViewDirection(vec3 cameraPosition, vec3 cameraForward, vec3 worldPosition) { + #ifdef CAMERA_ORTHOGRAPHIC + return -cameraForward; + #else + return normalize(cameraPosition - worldPosition); + #endif +} + +#endif diff --git a/packages/shader/src/ShaderLibrary/Common/WorldPosition.glsl b/packages/shader/src/ShaderLibrary/Common/WorldPosition.glsl new file mode 100644 index 0000000000..e3f232093e --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Common/WorldPosition.glsl @@ -0,0 +1,15 @@ +#ifndef WORLD_POSITION_INCLUDED +#define WORLD_POSITION_INCLUDED + +#ifdef MATERIAL_NEED_WORLD_POS + varying vec3 v_pos; +#endif + +void initWorldPosition(mat4 modelMat, vec4 position) { + #ifdef MATERIAL_NEED_WORLD_POS + vec4 temp_pos = modelMat * position; + v_pos = temp_pos.xyz / temp_pos.w; + #endif +} + +#endif diff --git a/packages/core/src/shaderlib/noise_common.glsl b/packages/shader/src/ShaderLibrary/Noise/NoiseCommon.glsl similarity index 81% rename from packages/core/src/shaderlib/noise_common.glsl rename to packages/shader/src/ShaderLibrary/Noise/NoiseCommon.glsl index 826079969e..1ff549124e 100644 --- a/packages/core/src/shaderlib/noise_common.glsl +++ b/packages/shader/src/ShaderLibrary/Noise/NoiseCommon.glsl @@ -1,3 +1,10 @@ +#ifndef NOISE_COMMON_INCLUDED +#define NOISE_COMMON_INCLUDED + +// Common helper functions for simplex noise. +// Algorithm: Ken Perlin, "Noise hardware" (2001) — simplex lattice improvement over classic Perlin noise (1985). +// GLSL implementation: Ian McEwan, Ashima Arts (MIT License) — https://github.com/ashima/webgl-noise + // Modulo 289 without a division (only multiplications) vec4 mod289( vec4 x ) { @@ -93,3 +100,5 @@ vec2 fade( vec2 t ) { #define Kzo 0.416666666667 // 1/2-1/6*2 #define jitter 1.0 // smaller jitter gives more regular pattern #define jitter1 0.8 // smaller jitter gives less errors in F1 F2 + +#endif // NOISE_COMMON_INCLUDED diff --git a/packages/core/src/shaderlib/noise_simplex_3D_grad.glsl b/packages/shader/src/ShaderLibrary/Noise/NoiseSimplexGrad.glsl similarity index 74% rename from packages/core/src/shaderlib/noise_simplex_3D_grad.glsl rename to packages/shader/src/ShaderLibrary/Noise/NoiseSimplexGrad.glsl index 8b106bc0fa..801ce7beb3 100644 --- a/packages/core/src/shaderlib/noise_simplex_3D_grad.glsl +++ b/packages/shader/src/ShaderLibrary/Noise/NoiseSimplexGrad.glsl @@ -1,16 +1,14 @@ -// -// Description : Array and textureless GLSL 2D/3D/4D simplex -// noise functions. -// Author : Ian McEwan, Ashima Arts. -// Maintainer : stegu -// Lastmod : 20150104 (JcBernack) -// License : Copyright (C) 2011 Ashima Arts. All rights reserved. -// Distributed under the MIT License. See LICENSE file. -// https://github.com/ashima/webgl-noise -// https://github.com/stegu/webgl-noise -// - -float simplex( vec3 v, out vec3 gradient ) { +#ifndef NOISE_SIMPLEX_GRAD_INCLUDED +#define NOISE_SIMPLEX_GRAD_INCLUDED + +// 3D simplex noise analytical gradient. +// Algorithm: Ken Perlin, "Noise hardware" (2001) — simplex lattice improvement over classic Perlin noise (1985). +// Curl noise: Robert Bridson et al., "Curl-noise for procedural fluid flow" (2007). +// GLSL implementation: Ian McEwan, Ashima Arts (MIT License) — https://github.com/ashima/webgl-noise + +#include "Noise/NoiseCommon.glsl" + +vec3 simplexGrad( vec3 v ) { const vec2 C = vec2( 1.0 / 6.0, 1.0 / 3.0 ); const vec4 D = vec4( 0.0, 0.5, 1.0, 2.0 ); @@ -78,12 +76,12 @@ float simplex( vec3 v, out vec3 gradient ) { vec4 m4 = m2 * m2; vec4 pdotx = vec4( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 ), dot( p3, x3 ) ); - // Determine noise gradient + // Compute and return noise gradient vec4 temp = m2 * m * pdotx; - gradient = - 8.0 * ( temp.x * x0 + temp.y * x1 + temp.z * x2 + temp.w * x3 ); - gradient += m4.x * p0 + m4.y * p1 + m4.z * p2 + m4.w * p3; - gradient *= 42.0; - - return 42.0 * dot( m4, pdotx ); + vec3 grad = - 8.0 * ( temp.x * x0 + temp.y * x1 + temp.z * x2 + temp.w * x3 ); + grad += m4.x * p0 + m4.y * p1 + m4.z * p2 + m4.w * p3; + return grad * 42.0; } + +#endif // NOISE_SIMPLEX_GRAD_INCLUDED diff --git a/packages/shader/src/shaders/shadingPBR/AttributesPBR.glsl b/packages/shader/src/ShaderLibrary/PBR/AttributesPBR.glsl similarity index 100% rename from packages/shader/src/shaders/shadingPBR/AttributesPBR.glsl rename to packages/shader/src/ShaderLibrary/PBR/AttributesPBR.glsl diff --git a/packages/shader/src/shaders/shadingPBR/BSDF.glsl b/packages/shader/src/ShaderLibrary/PBR/BSDF.glsl similarity index 99% rename from packages/shader/src/shaders/shadingPBR/BSDF.glsl rename to packages/shader/src/ShaderLibrary/PBR/BSDF.glsl index 06f0b5123f..12e6969eed 100644 --- a/packages/shader/src/shaders/shadingPBR/BSDF.glsl +++ b/packages/shader/src/ShaderLibrary/PBR/BSDF.glsl @@ -1,7 +1,7 @@ #ifndef BSDF_INCLUDED #define BSDF_INCLUDED -#include "Refraction.glsl" +#include "PBR/Refraction.glsl" #define MIN_PERCEPTUAL_ROUGHNESS 0.045 #define MIN_ROUGHNESS 0.002025 diff --git a/packages/shader/src/shaders/shadingPBR/ForwardPassPBR.glsl b/packages/shader/src/ShaderLibrary/PBR/ForwardPassPBR.glsl similarity index 88% rename from packages/shader/src/shaders/shadingPBR/ForwardPassPBR.glsl rename to packages/shader/src/ShaderLibrary/PBR/ForwardPassPBR.glsl index 99e441102f..c24a7463ed 100644 --- a/packages/shader/src/shaders/shadingPBR/ForwardPassPBR.glsl +++ b/packages/shader/src/ShaderLibrary/PBR/ForwardPassPBR.glsl @@ -1,19 +1,19 @@ #ifndef FORWARD_PASS_PBR_INCLUDED #define FORWARD_PASS_PBR_INCLUDED -#include "Common.glsl" -#include "Fog.glsl" -#include "Transform.glsl" -#include "Skin.glsl" -#include "BlendShape.glsl" -#include "Shadow.glsl" - -#include "AttributesPBR.glsl" -#include "VaryingsPBR.glsl" -#include "LightDirectPBR.glsl" -#include "LightIndirectPBR.glsl" -#include "VertexPBR.glsl" -#include "FragmentPBR.glsl" +#include "Common/Common.glsl" +#include "Common/Fog.glsl" +#include "Common/Transform.glsl" +#include "Skin/Skin.glsl" +#include "Skin/BlendShape.glsl" +#include "Shadow/Shadow.glsl" + +#include "PBR/AttributesPBR.glsl" +#include "PBR/VaryingsPBR.glsl" +#include "PBR/LightDirectPBR.glsl" +#include "PBR/LightIndirectPBR.glsl" +#include "PBR/VertexPBR.glsl" +#include "PBR/FragmentPBR.glsl" Varyings PBRVertex(Attributes attributes) { diff --git a/packages/shader/src/shaders/shadingPBR/FragmentPBR.glsl b/packages/shader/src/ShaderLibrary/PBR/FragmentPBR.glsl similarity index 99% rename from packages/shader/src/shaders/shadingPBR/FragmentPBR.glsl rename to packages/shader/src/ShaderLibrary/PBR/FragmentPBR.glsl index 5f29c14e84..f6301ae141 100644 --- a/packages/shader/src/shaders/shadingPBR/FragmentPBR.glsl +++ b/packages/shader/src/ShaderLibrary/PBR/FragmentPBR.glsl @@ -1,7 +1,7 @@ #ifndef MATERIAL_INPUT_PBR_INCLUDED #define MATERIAL_INPUT_PBR_INCLUDED -#include "Normal.glsl" +#include "Common/Normal.glsl" float material_AlphaCutoff; vec4 material_BaseColor; diff --git a/packages/shader/src/shaders/shadingPBR/LightDirectPBR.glsl b/packages/shader/src/ShaderLibrary/PBR/LightDirectPBR.glsl similarity index 98% rename from packages/shader/src/shaders/shadingPBR/LightDirectPBR.glsl rename to packages/shader/src/ShaderLibrary/PBR/LightDirectPBR.glsl index b65cd77aab..6c190ffaf2 100644 --- a/packages/shader/src/shaders/shadingPBR/LightDirectPBR.glsl +++ b/packages/shader/src/ShaderLibrary/PBR/LightDirectPBR.glsl @@ -18,9 +18,9 @@ #define FUNCTION_SHEEN_LOBE sheenLobe #endif -#include "BSDF.glsl" -#include "Light.glsl" -#include "ReflectionLobe.glsl" +#include "PBR/BSDF.glsl" +#include "Common/Light.glsl" +#include "PBR/ReflectionLobe.glsl" void surfaceShading(Varyings varyings, SurfaceData surfaceData, BSDFData bsdfData, vec3 incidentDirection, vec3 lightColor, inout vec3 totalDiffuseColor, inout vec3 totalSpecularColor) { diff --git a/packages/shader/src/shaders/shadingPBR/LightIndirectFunctions.glsl b/packages/shader/src/ShaderLibrary/PBR/LightIndirectFunctions.glsl similarity index 100% rename from packages/shader/src/shaders/shadingPBR/LightIndirectFunctions.glsl rename to packages/shader/src/ShaderLibrary/PBR/LightIndirectFunctions.glsl diff --git a/packages/shader/src/shaders/shadingPBR/LightIndirectPBR.glsl b/packages/shader/src/ShaderLibrary/PBR/LightIndirectPBR.glsl similarity index 98% rename from packages/shader/src/shaders/shadingPBR/LightIndirectPBR.glsl rename to packages/shader/src/ShaderLibrary/PBR/LightIndirectPBR.glsl index 2e47a3fa08..a5219ddf99 100644 --- a/packages/shader/src/shaders/shadingPBR/LightIndirectPBR.glsl +++ b/packages/shader/src/ShaderLibrary/PBR/LightIndirectPBR.glsl @@ -15,7 +15,7 @@ #define FUNCTION_SHEEN_IBL evaluateSheenIBL #endif -#include "LightIndirectFunctions.glsl" +#include "PBR/LightIndirectFunctions.glsl" // ------------------------Diffuse------------------------ diff --git a/packages/shader/src/shaders/shadingPBR/ReflectionLobe.glsl b/packages/shader/src/ShaderLibrary/PBR/ReflectionLobe.glsl similarity index 100% rename from packages/shader/src/shaders/shadingPBR/ReflectionLobe.glsl rename to packages/shader/src/ShaderLibrary/PBR/ReflectionLobe.glsl diff --git a/packages/shader/src/shaders/shadingPBR/Refraction.glsl b/packages/shader/src/ShaderLibrary/PBR/Refraction.glsl similarity index 100% rename from packages/shader/src/shaders/shadingPBR/Refraction.glsl rename to packages/shader/src/ShaderLibrary/PBR/Refraction.glsl diff --git a/packages/shader/src/shaders/shadingPBR/VaryingsPBR.glsl b/packages/shader/src/ShaderLibrary/PBR/VaryingsPBR.glsl similarity index 100% rename from packages/shader/src/shaders/shadingPBR/VaryingsPBR.glsl rename to packages/shader/src/ShaderLibrary/PBR/VaryingsPBR.glsl diff --git a/packages/shader/src/shaders/shadingPBR/VertexPBR.glsl b/packages/shader/src/ShaderLibrary/PBR/VertexPBR.glsl similarity index 100% rename from packages/shader/src/shaders/shadingPBR/VertexPBR.glsl rename to packages/shader/src/ShaderLibrary/PBR/VertexPBR.glsl diff --git a/packages/core/src/shaderlib/particle/horizontal_billboard.glsl b/packages/shader/src/ShaderLibrary/Particle/Billboard/HorizontalBillboard.glsl similarity index 89% rename from packages/core/src/shaderlib/particle/horizontal_billboard.glsl rename to packages/shader/src/ShaderLibrary/Particle/Billboard/HorizontalBillboard.glsl index b9649f94e7..35bd923724 100644 --- a/packages/core/src/shaderlib/particle/horizontal_billboard.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Billboard/HorizontalBillboard.glsl @@ -1,3 +1,6 @@ +#ifndef HORIZONTAL_BILLBOARD_INCLUDED +#define HORIZONTAL_BILLBOARD_INCLUDED + #ifdef RENDERER_MODE_HORIZONTAL_BILLBOARD vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; const vec3 sideVector = vec3(1.0, 0.0, 0.0); @@ -18,4 +21,6 @@ mat2 rotation = mat2(c, -s, s, c); corner = rotation * corner; center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector); -#endif \ No newline at end of file +#endif + +#endif diff --git a/packages/core/src/shaderlib/particle/sphere_billboard.glsl b/packages/shader/src/ShaderLibrary/Particle/Billboard/SphereBillboard.glsl similarity index 94% rename from packages/core/src/shaderlib/particle/sphere_billboard.glsl rename to packages/shader/src/ShaderLibrary/Particle/Billboard/SphereBillboard.glsl index 1a14460c10..d406eba812 100644 --- a/packages/core/src/shaderlib/particle/sphere_billboard.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Billboard/SphereBillboard.glsl @@ -1,3 +1,6 @@ +#ifndef SPHERE_BILLBOARD_INCLUDED +#define SPHERE_BILLBOARD_INCLUDED + #ifdef RENDERER_MODE_SPHERE_BILLBOARD vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; vec3 sideVector = normalize(cross(camera_Forward, camera_Up)); @@ -26,4 +29,6 @@ center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector); } #endif -#endif \ No newline at end of file +#endif + +#endif diff --git a/packages/core/src/shaderlib/particle/stretched_billboard.glsl b/packages/shader/src/ShaderLibrary/Particle/Billboard/StretchedBillboard.glsl similarity index 91% rename from packages/core/src/shaderlib/particle/stretched_billboard.glsl rename to packages/shader/src/ShaderLibrary/Particle/Billboard/StretchedBillboard.glsl index fed7b0dd35..69da1ad0c2 100644 --- a/packages/core/src/shaderlib/particle/stretched_billboard.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Billboard/StretchedBillboard.glsl @@ -1,3 +1,6 @@ +#ifndef STRETCHED_BILLBOARD_INCLUDED +#define STRETCHED_BILLBOARD_INCLUDED + #ifdef RENDERER_MODE_STRETCHED_BILLBOARD vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; vec3 velocity = rotationByQuaternions(renderer_SizeScale * localVelocity, worldRotation) + worldVelocity; @@ -17,4 +20,6 @@ float speed = length(velocity); // TODO: center += sign(renderer_SizeScale.x) * (sign(renderer_StretchedBillboardLengthScale) * size.x * corner.x * sideVector + (speed * renderer_StretchedBillboardSpeedScale + size.y * renderer_StretchedBillboardLengthScale) * corner.y * cameraUpVector); -#endif \ No newline at end of file +#endif + +#endif diff --git a/packages/core/src/shaderlib/particle/vertical_billboard.glsl b/packages/shader/src/ShaderLibrary/Particle/Billboard/VerticalBillboard.glsl similarity index 88% rename from packages/core/src/shaderlib/particle/vertical_billboard.glsl rename to packages/shader/src/ShaderLibrary/Particle/Billboard/VerticalBillboard.glsl index d5d3ad1119..43552ca970 100644 --- a/packages/core/src/shaderlib/particle/vertical_billboard.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Billboard/VerticalBillboard.glsl @@ -1,3 +1,6 @@ +#ifndef VERTICAL_BILLBOARD_INCLUDED +#define VERTICAL_BILLBOARD_INCLUDED + #ifdef RENDERER_MODE_VERTICAL_BILLBOARD vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; // Billboard模式z轴无效 const vec3 cameraUpVector = vec3(0.0, 1.0, 0.0); @@ -10,4 +13,6 @@ corner = rotation * corner * cos(0.78539816339744830961566084581988); // TODO:临时缩小cos45,不确定U3D原因 corner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge); center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * cameraUpVector); -#endif \ No newline at end of file +#endif + +#endif diff --git a/packages/core/src/shaderlib/particle/color_over_lifetime_module.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/ColorOverLifetime.glsl similarity index 65% rename from packages/core/src/shaderlib/particle/color_over_lifetime_module.glsl rename to packages/shader/src/ShaderLibrary/Particle/Module/ColorOverLifetime.glsl index 56127ce487..29a608b86a 100644 --- a/packages/core/src/shaderlib/particle/color_over_lifetime_module.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Module/ColorOverLifetime.glsl @@ -1,13 +1,16 @@ +#ifndef COLOR_OVER_LIFETIME_INCLUDED +#define COLOR_OVER_LIFETIME_INCLUDED + #if defined(RENDERER_COL_GRADIENT) || defined(RENDERER_COL_RANDOM_GRADIENTS) - uniform vec4 renderer_COLMaxGradientColor[4]; // x:time y:r z:g w:b - uniform vec2 renderer_COLMaxGradientAlpha[4]; // x:time y:alpha + vec4 renderer_COLMaxGradientColor[4]; // x:time y:r z:g w:b + vec2 renderer_COLMaxGradientAlpha[4]; // x:time y:alpha #ifdef RENDERER_COL_RANDOM_GRADIENTS - uniform vec4 renderer_COLMinGradientColor[4]; // x:time y:r z:g w:b - uniform vec2 renderer_COLMinGradientAlpha[4]; // x:time y:alpha + vec4 renderer_COLMinGradientColor[4]; // x:time y:r z:g w:b + vec2 renderer_COLMinGradientAlpha[4]; // x:time y:alpha #endif - uniform vec4 renderer_COLGradientKeysMaxTime; // x: minColorKeysMaxTime, y: minAlphaKeysMaxTime, z: maxColorKeysMaxTime, w: maxAlphaKeysMaxTime + vec4 renderer_COLGradientKeysMaxTime; // x: minColorKeysMaxTime, y: minAlphaKeysMaxTime, z: maxColorKeysMaxTime, w: maxAlphaKeysMaxTime #endif @@ -26,3 +29,5 @@ vec4 computeParticleColor(in vec4 color, in float normalizedAge) { return color; } + +#endif diff --git a/packages/core/src/shaderlib/particle/force_over_lifetime_module.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/ForceOverLifetime.glsl similarity index 88% rename from packages/core/src/shaderlib/particle/force_over_lifetime_module.glsl rename to packages/shader/src/ShaderLibrary/Particle/Module/ForceOverLifetime.glsl index 612007f30a..f4c1625b08 100644 --- a/packages/core/src/shaderlib/particle/force_over_lifetime_module.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Module/ForceOverLifetime.glsl @@ -1,28 +1,31 @@ +#ifndef FORCE_OVER_LIFETIME_INCLUDED +#define FORCE_OVER_LIFETIME_INCLUDED + #if defined(RENDERER_FOL_CONSTANT_MODE) || defined(RENDERER_FOL_CURVE_MODE) #define _FOL_MODULE_ENABLED #endif #ifdef _FOL_MODULE_ENABLED - uniform int renderer_FOLSpace; + int renderer_FOLSpace; #ifdef RENDERER_FOL_CONSTANT_MODE - uniform vec3 renderer_FOLMaxConst; + vec3 renderer_FOLMaxConst; #ifdef RENDERER_FOL_IS_RANDOM_TWO - uniform vec3 renderer_FOLMinConst; + vec3 renderer_FOLMinConst; #endif #endif #ifdef RENDERER_FOL_CURVE_MODE - uniform vec2 renderer_FOLMaxGradientX[4]; - uniform vec2 renderer_FOLMaxGradientY[4]; - uniform vec2 renderer_FOLMaxGradientZ[4]; + vec2 renderer_FOLMaxGradientX[4]; + vec2 renderer_FOLMaxGradientY[4]; + vec2 renderer_FOLMaxGradientZ[4]; #ifdef RENDERER_FOL_IS_RANDOM_TWO - uniform vec2 renderer_FOLMinGradientX[4]; - uniform vec2 renderer_FOLMinGradientY[4]; - uniform vec2 renderer_FOLMinGradientZ[4]; + vec2 renderer_FOLMinGradientX[4]; + vec2 renderer_FOLMinGradientY[4]; + vec2 renderer_FOLMinGradientZ[4]; #endif #endif @@ -48,7 +51,7 @@ float finalAcceleration = mix(lastKey.y, key.y, timeOffset / timeRange); velocityCumulative += 0.5 * timeOffset * (finalAcceleration + lastKey.y); break; - } else { + } else { cumulativeValue += computeDisplacementIntegral(timeRange, timeRange, lastKey.y, key.y, velocityCumulative); velocityCumulative += 0.5 * timeRange * (lastKey.y + key.y); } @@ -89,4 +92,6 @@ #endif return forcePosition; } -#endif \ No newline at end of file +#endif + +#endif diff --git a/packages/core/src/shaderlib/particle/limit_velocity_over_lifetime_module.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/LimitVelocityOverLifetime.glsl similarity index 82% rename from packages/core/src/shaderlib/particle/limit_velocity_over_lifetime_module.glsl rename to packages/shader/src/ShaderLibrary/Particle/Module/LimitVelocityOverLifetime.glsl index fd3d27bfea..d6430c7430 100644 --- a/packages/core/src/shaderlib/particle/limit_velocity_over_lifetime_module.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Module/LimitVelocityOverLifetime.glsl @@ -1,19 +1,22 @@ +#ifndef LIMIT_VELOCITY_OVER_LIFETIME_INCLUDED +#define LIMIT_VELOCITY_OVER_LIFETIME_INCLUDED + #ifdef RENDERER_LVL_MODULE_ENABLED - uniform int renderer_LVLSpace; - uniform float renderer_LVLDampen; + int renderer_LVLSpace; + float renderer_LVLDampen; // Scalar limit #ifndef RENDERER_LVL_SEPARATE_AXES #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE - uniform float renderer_LVLSpeedMaxConst; + float renderer_LVLSpeedMaxConst; #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO - uniform float renderer_LVLSpeedMinConst; + float renderer_LVLSpeedMinConst; #endif #endif #ifdef RENDERER_LVL_SPEED_CURVE_MODE - uniform vec2 renderer_LVLSpeedMaxCurve[4]; + vec2 renderer_LVLSpeedMaxCurve[4]; #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO - uniform vec2 renderer_LVLSpeedMinCurve[4]; + vec2 renderer_LVLSpeedMinCurve[4]; #endif #endif #endif @@ -21,28 +24,28 @@ // Per-axis limit #ifdef RENDERER_LVL_SEPARATE_AXES #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE - uniform vec3 renderer_LVLSpeedMaxConstVector; + vec3 renderer_LVLSpeedMaxConstVector; #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO - uniform vec3 renderer_LVLSpeedMinConstVector; + vec3 renderer_LVLSpeedMinConstVector; #endif #endif #ifdef RENDERER_LVL_SPEED_CURVE_MODE - uniform vec2 renderer_LVLSpeedXMaxCurve[4]; - uniform vec2 renderer_LVLSpeedYMaxCurve[4]; - uniform vec2 renderer_LVLSpeedZMaxCurve[4]; + vec2 renderer_LVLSpeedXMaxCurve[4]; + vec2 renderer_LVLSpeedYMaxCurve[4]; + vec2 renderer_LVLSpeedZMaxCurve[4]; #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO - uniform vec2 renderer_LVLSpeedXMinCurve[4]; - uniform vec2 renderer_LVLSpeedYMinCurve[4]; - uniform vec2 renderer_LVLSpeedZMinCurve[4]; + vec2 renderer_LVLSpeedXMinCurve[4]; + vec2 renderer_LVLSpeedYMinCurve[4]; + vec2 renderer_LVLSpeedZMinCurve[4]; #endif #endif #endif // Drag curve #ifdef RENDERER_LVL_DRAG_CURVE_MODE - uniform vec2 renderer_LVLDragMaxCurve[4]; + vec2 renderer_LVLDragMaxCurve[4]; #ifdef RENDERER_LVL_DRAG_IS_RANDOM_TWO - uniform vec2 renderer_LVLDragMinCurve[4]; + vec2 renderer_LVLDragMinCurve[4]; #endif #endif @@ -114,3 +117,5 @@ } #endif + +#endif diff --git a/packages/shader/src/ShaderLibrary/Particle/Module/NoiseModule.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/NoiseModule.glsl new file mode 100644 index 0000000000..39fb9dc0bc --- /dev/null +++ b/packages/shader/src/ShaderLibrary/Particle/Module/NoiseModule.glsl @@ -0,0 +1,97 @@ +#ifndef NOISE_MODULE_INCLUDED +#define NOISE_MODULE_INCLUDED + +#ifdef RENDERER_NOISE_MODULE_ENABLED + +#include "Noise/NoiseCommon.glsl" +#include "Noise/NoiseSimplexGrad.glsl" + +vec4 renderer_NoiseParams; // xyz = strength (constant mode only), w = frequency +vec4 renderer_NoiseOctaveParams; // x = scrollSpeed, y = octaveCount, z = octaveIntensityMultiplier, w = octaveFrequencyMultiplier + +#ifdef RENDERER_NOISE_STRENGTH_CURVE + vec2 renderer_NoiseStrengthMaxCurveX[4]; + #ifdef RENDERER_NOISE_IS_SEPARATE + vec2 renderer_NoiseStrengthMaxCurveY[4]; + vec2 renderer_NoiseStrengthMaxCurveZ[4]; + #endif + #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO + vec2 renderer_NoiseStrengthMinCurveX[4]; + #ifdef RENDERER_NOISE_IS_SEPARATE + vec2 renderer_NoiseStrengthMinCurveY[4]; + vec2 renderer_NoiseStrengthMinCurveZ[4]; + #endif + #endif +#else + #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO + vec3 renderer_NoiseStrengthMinConst; + #endif +#endif + +vec3 sampleCurlNoise3D(vec3 coord) { + float axisOffset = 100.0; + vec3 gradX = simplexGrad(vec3(coord.z, coord.y, coord.x)); + vec3 gradY = simplexGrad(vec3(coord.x + axisOffset, coord.z, coord.y)); + vec3 gradZ = simplexGrad(vec3(coord.y, coord.x + axisOffset, coord.z)); + return vec3( + gradZ.x - gradY.y, + gradX.x - gradZ.y, + gradY.x - gradX.y + ); +} + +vec3 computeNoiseVelocity(vec3 currentPosition, float normalizedAge) { + vec3 coord = currentPosition * renderer_NoiseParams.w + + vec3(renderer_CurrentTime * renderer_NoiseOctaveParams.x); + + int octaveCount = int(renderer_NoiseOctaveParams.y); + float octaveIntensityMultiplier = renderer_NoiseOctaveParams.z; + float octaveFrequencyMultiplier = renderer_NoiseOctaveParams.w; + + vec3 noiseValue = sampleCurlNoise3D(coord); + float totalAmplitude = 1.0; + + // Unrolled octave loop (GLSL ES 1.0 requires constant loop bounds) + if (octaveCount >= 2) { + float amplitude = octaveIntensityMultiplier; + totalAmplitude += amplitude; + noiseValue += amplitude * sampleCurlNoise3D(coord * octaveFrequencyMultiplier); + + if (octaveCount >= 3) { + amplitude *= octaveIntensityMultiplier; + totalAmplitude += amplitude; + noiseValue += amplitude * sampleCurlNoise3D(coord * octaveFrequencyMultiplier * octaveFrequencyMultiplier); + } + } + + // Evaluate strength (supports Constant, TwoConstants, Curve, TwoCurves). + vec3 strength; + #ifdef RENDERER_NOISE_STRENGTH_CURVE + float sx = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveX, normalizedAge); + #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO + sx = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveX, normalizedAge), sx, a_Random0.z); + #endif + #ifdef RENDERER_NOISE_IS_SEPARATE + float sy = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveY, normalizedAge); + float sz = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveZ, normalizedAge); + #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO + sy = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveY, normalizedAge), sy, a_Random0.z); + sz = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveZ, normalizedAge), sz, a_Random0.z); + #endif + strength = vec3(sx, sy, sz); + #else + strength = vec3(sx); + #endif + #else + strength = renderer_NoiseParams.xyz; + #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO + strength = mix(renderer_NoiseStrengthMinConst, strength, a_Random0.z); + #endif + #endif + + return (noiseValue / totalAmplitude) * strength; +} + +#endif + +#endif // NOISE_MODULE_INCLUDED diff --git a/packages/core/src/shaderlib/particle/rotation_over_lifetime_module.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/RotationOverLifetime.glsl similarity index 90% rename from packages/core/src/shaderlib/particle/rotation_over_lifetime_module.glsl rename to packages/shader/src/ShaderLibrary/Particle/Module/RotationOverLifetime.glsl index 226848bba8..97ccd2aed1 100644 --- a/packages/core/src/shaderlib/particle/rotation_over_lifetime_module.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Module/RotationOverLifetime.glsl @@ -1,21 +1,24 @@ +#ifndef ROTATION_OVER_LIFETIME_INCLUDED +#define ROTATION_OVER_LIFETIME_INCLUDED + #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE) #ifdef RENDERER_ROL_CURVE_MODE - uniform vec2 renderer_ROLMaxCurveZ[4]; + vec2 renderer_ROLMaxCurveZ[4]; #ifdef RENDERER_ROL_IS_SEPARATE - uniform vec2 renderer_ROLMaxCurveX[4]; - uniform vec2 renderer_ROLMaxCurveY[4]; + vec2 renderer_ROLMaxCurveX[4]; + vec2 renderer_ROLMaxCurveY[4]; #endif #ifdef RENDERER_ROL_IS_RANDOM_TWO - uniform vec2 renderer_ROLMinCurveZ[4]; + vec2 renderer_ROLMinCurveZ[4]; #ifdef RENDERER_ROL_IS_SEPARATE - uniform vec2 renderer_ROLMinCurveX[4]; - uniform vec2 renderer_ROLMinCurveY[4]; + vec2 renderer_ROLMinCurveX[4]; + vec2 renderer_ROLMinCurveY[4]; #endif #endif #else - uniform vec3 renderer_ROLMaxConst; + vec3 renderer_ROLMaxConst; #ifdef RENDERER_ROL_IS_RANDOM_TWO - uniform vec3 renderer_ROLMinConst; + vec3 renderer_ROLMinConst; #endif #endif #endif @@ -92,3 +95,5 @@ vec3 computeParticleRotationVec3(in vec3 rotation, in float age, in float normal return rotation; } #endif + +#endif diff --git a/packages/core/src/shaderlib/particle/size_over_lifetime_module.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/SizeOverLifetime.glsl similarity index 84% rename from packages/core/src/shaderlib/particle/size_over_lifetime_module.glsl rename to packages/shader/src/ShaderLibrary/Particle/Module/SizeOverLifetime.glsl index 06e65f243c..ea49d17fb1 100644 --- a/packages/core/src/shaderlib/particle/size_over_lifetime_module.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Module/SizeOverLifetime.glsl @@ -1,15 +1,18 @@ +#ifndef SIZE_OVER_LIFETIME_INCLUDED +#define SIZE_OVER_LIFETIME_INCLUDED + #ifdef RENDERER_SOL_CURVE_MODE - uniform vec2 renderer_SOLMaxCurveX[4]; // x:time y:value + vec2 renderer_SOLMaxCurveX[4]; // x:time y:value #ifdef RENDERER_SOL_IS_SEPARATE - uniform vec2 renderer_SOLMaxCurveY[4]; // x:time y:value - uniform vec2 renderer_SOLMaxCurveZ[4]; // x:time y:value + vec2 renderer_SOLMaxCurveY[4]; // x:time y:value + vec2 renderer_SOLMaxCurveZ[4]; // x:time y:value #endif #ifdef RENDERER_SOL_IS_RANDOM_TWO - uniform vec2 renderer_SOLMinCurveX[4]; // x:time y:value + vec2 renderer_SOLMinCurveX[4]; // x:time y:value #ifdef RENDERER_SOL_IS_SEPARATE - uniform vec2 renderer_SOLMinCurveY[4]; // x:time y:value - uniform vec2 renderer_SOLMinCurveZ[4]; // x:time y:value + vec2 renderer_SOLMinCurveY[4]; // x:time y:value + vec2 renderer_SOLMinCurveZ[4]; // x:time y:value #endif #endif #endif @@ -62,4 +65,6 @@ vec2 computeParticleSizeBillboard(in vec2 size, in float normalizedAge) { #endif return size; } -#endif \ No newline at end of file +#endif + +#endif diff --git a/packages/core/src/shaderlib/particle/texture_sheet_animation_module.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/TextureSheetAnimation.glsl similarity index 77% rename from packages/core/src/shaderlib/particle/texture_sheet_animation_module.glsl rename to packages/shader/src/ShaderLibrary/Particle/Module/TextureSheetAnimation.glsl index 7187dfcb2f..1cca1e217e 100644 --- a/packages/core/src/shaderlib/particle/texture_sheet_animation_module.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Module/TextureSheetAnimation.glsl @@ -1,10 +1,13 @@ +#ifndef TEXTURE_SHEET_ANIMATION_INCLUDED +#define TEXTURE_SHEET_ANIMATION_INCLUDED + #if defined(RENDERER_TSA_FRAME_CURVE) || defined(RENDERER_TSA_FRAME_RANDOM_CURVES) - uniform float renderer_TSACycles; - uniform vec3 renderer_TSATillingParams; // x:subU y:subV z:tileCount - uniform vec2 renderer_TSAFrameMaxCurve[4]; // x:time y:value + float renderer_TSACycles; + vec3 renderer_TSATillingParams; // x:subU y:subV z:tileCount + vec2 renderer_TSAFrameMaxCurve[4]; // x:time y:value #ifdef RENDERER_TSA_FRAME_RANDOM_CURVES - uniform vec2 renderer_TSAFrameMinCurve[4]; // x:time y:value + vec2 renderer_TSAFrameMinCurve[4]; // x:time y:value #endif #endif @@ -24,6 +27,8 @@ vec2 computeParticleUV(in vec2 uv, in float normalizedAge) { uv.x += tileRow - tileRowIndex; uv.y += tileRowIndex * renderer_TSATillingParams.y; #endif - + return uv; } + +#endif diff --git a/packages/core/src/shaderlib/particle/velocity_over_lifetime_module.glsl b/packages/shader/src/ShaderLibrary/Particle/Module/VelocityOverLifetime.glsl similarity index 78% rename from packages/core/src/shaderlib/particle/velocity_over_lifetime_module.glsl rename to packages/shader/src/ShaderLibrary/Particle/Module/VelocityOverLifetime.glsl index 19a96bc43e..bf8496fd92 100644 --- a/packages/core/src/shaderlib/particle/velocity_over_lifetime_module.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/Module/VelocityOverLifetime.glsl @@ -1,27 +1,30 @@ +#ifndef VELOCITY_OVER_LIFETIME_INCLUDED +#define VELOCITY_OVER_LIFETIME_INCLUDED + #if defined(RENDERER_VOL_CONSTANT_MODE) || defined(RENDERER_VOL_CURVE_MODE) #define _VOL_MODULE_ENABLED #endif #ifdef _VOL_MODULE_ENABLED - uniform int renderer_VOLSpace; + int renderer_VOLSpace; #ifdef RENDERER_VOL_CONSTANT_MODE - uniform vec3 renderer_VOLMaxConst; + vec3 renderer_VOLMaxConst; #ifdef RENDERER_VOL_IS_RANDOM_TWO - uniform vec3 renderer_VOLMinConst; + vec3 renderer_VOLMinConst; #endif #endif #ifdef RENDERER_VOL_CURVE_MODE - uniform vec2 renderer_VOLMaxGradientX[4]; // x:time y:value - uniform vec2 renderer_VOLMaxGradientY[4]; // x:time y:value - uniform vec2 renderer_VOLMaxGradientZ[4]; // x:time y:value + vec2 renderer_VOLMaxGradientX[4]; // x:time y:value + vec2 renderer_VOLMaxGradientY[4]; // x:time y:value + vec2 renderer_VOLMaxGradientZ[4]; // x:time y:value #ifdef RENDERER_VOL_IS_RANDOM_TWO - uniform vec2 renderer_VOLMinGradientX[4]; // x:time y:value - uniform vec2 renderer_VOLMinGradientY[4]; // x:time y:value - uniform vec2 renderer_VOLMinGradientZ[4]; // x:time y:value + vec2 renderer_VOLMinGradientX[4]; // x:time y:value + vec2 renderer_VOLMinGradientY[4]; // x:time y:value + vec2 renderer_VOLMinGradientZ[4]; // x:time y:value #endif #endif @@ -60,3 +63,5 @@ return velocityPosition; } #endif + +#endif diff --git a/packages/core/src/shaderlib/particle/particle_common.glsl b/packages/shader/src/ShaderLibrary/Particle/ParticleCommon.glsl similarity index 97% rename from packages/core/src/shaderlib/particle/particle_common.glsl rename to packages/shader/src/ShaderLibrary/Particle/ParticleCommon.glsl index ea26df257f..fd826e794f 100644 --- a/packages/core/src/shaderlib/particle/particle_common.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/ParticleCommon.glsl @@ -1,3 +1,6 @@ +#ifndef PARTICLE_COMMON_INCLUDED +#define PARTICLE_COMMON_INCLUDED + vec3 rotationByQuaternions(in vec3 v, in vec4 q) { return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v); } @@ -111,4 +114,6 @@ vec4 evaluateParticleGradient(in vec4 colorKeys[4], in float colorMaxTime, in ve } return value; -} \ No newline at end of file +} + +#endif diff --git a/packages/core/src/shaderlib/particle/particle_feedback_simulation.glsl b/packages/shader/src/ShaderLibrary/Particle/ParticleFeedback.glsl similarity index 82% rename from packages/core/src/shaderlib/particle/particle_feedback_simulation.glsl rename to packages/shader/src/ShaderLibrary/Particle/ParticleFeedback.glsl index b4efd52087..3ab357fc33 100644 --- a/packages/core/src/shaderlib/particle/particle_feedback_simulation.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/ParticleFeedback.glsl @@ -1,39 +1,43 @@ +#ifndef PARTICLE_FEEDBACK_INCLUDED +#define PARTICLE_FEEDBACK_INCLUDED + // Transform Feedback update shader for particle simulation. -// Update order: VOL/FOL → Dampen → Drag → Position. +// Update order: VOL/FOL -> Dampen -> Drag -> Position. // Runs once per particle per frame (no rasterization). // Previous frame TF data -attribute vec3 a_FeedbackPosition; -attribute vec3 a_FeedbackVelocity; +vec3 a_FeedbackPosition; +vec3 a_FeedbackVelocity; // Per-particle instance data -attribute vec4 a_ShapePositionStartLifeTime; -attribute vec4 a_DirectionTime; -attribute vec3 a_StartSize; -attribute float a_StartSpeed; -attribute vec4 a_Random0; -attribute vec4 a_Random1; -attribute vec3 a_SimulationWorldPosition; -attribute vec4 a_SimulationWorldRotation; -attribute vec4 a_Random2; +vec4 a_ShapePositionStartLifeTime; +vec4 a_DirectionTime; +vec3 a_StartSize; +float a_StartSpeed; +vec4 a_Random0; +vec4 a_Random1; +vec3 a_SimulationWorldPosition; +vec4 a_SimulationWorldRotation; +vec4 a_Random2; // Uniforms -uniform float renderer_CurrentTime; -uniform float renderer_DeltaTime; -uniform vec3 renderer_Gravity; -uniform vec2 renderer_LVLDragConstant; -uniform vec3 renderer_WorldPosition; -uniform vec4 renderer_WorldRotation; -uniform int renderer_SimulationSpace; +float renderer_CurrentTime; +float renderer_DeltaTime; +vec3 renderer_Gravity; +vec2 renderer_LVLDragConstant; +vec3 renderer_WorldPosition; +vec4 renderer_WorldRotation; +int renderer_SimulationSpace; // TF outputs -varying vec3 v_FeedbackPosition; -varying vec3 v_FeedbackVelocity; +vec3 v_FeedbackPosition; +vec3 v_FeedbackVelocity; -#include -#include -#include -#include +#include +#include +#include +#include +#include // Get VOL instantaneous velocity at normalizedAge vec3 getVOLVelocity(float normalizedAge) { @@ -139,7 +143,7 @@ void main() { } #endif - // FOL acceleration → velocity delta (always persisted, like gravity) + // FOL acceleration -> velocity delta (always persisted, like gravity) vec3 folDeltaLocal = vec3(0.0); #ifdef _FOL_MODULE_ENABLED vec3 folAcc = getFOLAcceleration(normalizedAge); @@ -227,19 +231,32 @@ void main() { // World mode: position in world space, velocity rotated to world // ===================================================== // FOL is now fully in localVelocity (both local and world-space FOL). - // Only VOL overlay needs to be added here. + // VOL and Noise overlays are added here (not persisted). + vec3 totalVelocity; if (renderer_SimulationSpace == 0) { - // Local: integrate in local space - totalVelocity = localVelocity + volLocal - + rotationByQuaternions(volWorld, invWorldRotation); + totalVelocity = localVelocity + volLocal + rotationByQuaternions(volWorld, invWorldRotation); } else { - // World: integrate in world space totalVelocity = rotationByQuaternions(localVelocity + volLocal, worldRotation) + volWorld; } + #ifdef RENDERER_NOISE_MODULE_ENABLED + // Use analytical base position (birth + initial velocity * age) instead of + // a_FeedbackPosition to avoid feedback loop: position → noise → velocity → position + vec3 noiseBasePos; + if (renderer_SimulationSpace == 0) { + noiseBasePos = a_ShapePositionStartLifeTime.xyz + a_DirectionTime.xyz * a_StartSpeed * age; + } else { + noiseBasePos = rotationByQuaternions( + a_ShapePositionStartLifeTime.xyz + a_DirectionTime.xyz * a_StartSpeed * age, + worldRotation) + a_SimulationWorldPosition; + } + totalVelocity += computeNoiseVelocity(noiseBasePos, normalizedAge); + #endif vec3 position = a_FeedbackPosition + totalVelocity * dt; v_FeedbackPosition = position; v_FeedbackVelocity = localVelocity; gl_Position = vec4(0.0); } + +#endif diff --git a/packages/core/src/shaderlib/particle/particle_mesh.glsl b/packages/shader/src/ShaderLibrary/Particle/ParticleMesh.glsl similarity index 96% rename from packages/core/src/shaderlib/particle/particle_mesh.glsl rename to packages/shader/src/ShaderLibrary/Particle/ParticleMesh.glsl index 8b8988fbe8..0b44919fe5 100644 --- a/packages/core/src/shaderlib/particle/particle_mesh.glsl +++ b/packages/shader/src/ShaderLibrary/Particle/ParticleMesh.glsl @@ -1,3 +1,6 @@ +#ifndef PARTICLE_MESH_INCLUDED +#define PARTICLE_MESH_INCLUDED + // Only support local alignment mode #ifdef RENDERER_MODE_MESH #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE) @@ -44,4 +47,6 @@ #ifdef RENDERER_ENABLE_VERTEXCOLOR v_MeshColor = COLOR_0; #endif -#endif \ No newline at end of file +#endif + +#endif diff --git a/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomBlurH.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomBlurH.glsl new file mode 100644 index 0000000000..efcc55ed20 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomBlurH.glsl @@ -0,0 +1,28 @@ +#ifndef BLOOM_BLUR_H +#define BLOOM_BLUR_H + +#include "PostProcess/PostCommon.glsl" + +mediump sampler2D renderer_BlitTexture; +vec4 renderer_texelSize; + +void frag(Varyings v) { + vec2 texelSize = renderer_texelSize.xy * 2.0; + + // 9-tap gaussian blur on the downsampled source + mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v.v_uv - vec2(texelSize.x * 4.0, 0.0)); + mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v.v_uv - vec2(texelSize.x * 3.0, 0.0)); + mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v.v_uv - vec2(texelSize.x * 2.0, 0.0)); + mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v.v_uv - vec2(texelSize.x * 1.0, 0.0)); + mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v.v_uv); + mediump vec4 c5 = texture2DSRGB(renderer_BlitTexture, v.v_uv + vec2(texelSize.x * 1.0, 0.0)); + mediump vec4 c6 = texture2DSRGB(renderer_BlitTexture, v.v_uv + vec2(texelSize.x * 2.0, 0.0)); + mediump vec4 c7 = texture2DSRGB(renderer_BlitTexture, v.v_uv + vec2(texelSize.x * 3.0, 0.0)); + mediump vec4 c8 = texture2DSRGB(renderer_BlitTexture, v.v_uv + vec2(texelSize.x * 4.0, 0.0)); + + gl_FragColor = c0 * 0.01621622 + c1 * 0.05405405 + c2 * 0.12162162 + c3 * 0.19459459 + + c4 * 0.22702703 + + c5 * 0.19459459 + c6 * 0.12162162 + c7 * 0.05405405 + c8 * 0.01621622; +} + +#endif diff --git a/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomBlurV.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomBlurV.glsl new file mode 100644 index 0000000000..651860dec0 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomBlurV.glsl @@ -0,0 +1,24 @@ +#ifndef BLOOM_BLUR_V +#define BLOOM_BLUR_V + +#include "PostProcess/PostCommon.glsl" + +mediump sampler2D renderer_BlitTexture; +vec4 renderer_texelSize; + +void frag(Varyings v) { + vec2 texelSize = renderer_texelSize.xy; + + // Optimized bilinear 5-tap gaussian on the same-sized source (9-tap equivalent) + mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v.v_uv - vec2(0.0, texelSize.y * 3.23076923)); + mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v.v_uv - vec2(0.0, texelSize.y * 1.38461538)); + mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v.v_uv); + mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v.v_uv + vec2(0.0, texelSize.y * 1.38461538)); + mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v.v_uv + vec2(0.0, texelSize.y * 3.23076923)); + + gl_FragColor = c0 * 0.07027027 + c1 * 0.31621622 + + c2 * 0.22702703 + + c3 * 0.31621622 + c4 * 0.07027027; +} + +#endif diff --git a/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomPrefilter.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomPrefilter.glsl new file mode 100644 index 0000000000..1320b5f017 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomPrefilter.glsl @@ -0,0 +1,60 @@ +#ifndef BLOOM_PREFILTER +#define BLOOM_PREFILTER + +#include "PostProcess/PostCommon.glsl" + +mediump sampler2D renderer_BlitTexture; +vec4 material_BloomParams; +vec4 renderer_texelSize; + +void frag(Varyings v) { + #ifdef BLOOM_HQ + vec2 texelSize = renderer_texelSize.xy; + mediump vec4 A = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(-1.0, -1.0)); + mediump vec4 B = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(0.0, -1.0)); + mediump vec4 C = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(1.0, -1.0)); + mediump vec4 D = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(-0.5, -0.5)); + mediump vec4 E = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(0.5, -0.5)); + mediump vec4 F = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(-1.0, 0.0)); + mediump vec4 G = texture2DSRGB(renderer_BlitTexture, v.v_uv); + mediump vec4 H = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(1.0, 0.0)); + mediump vec4 I = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(-0.5, 0.5)); + mediump vec4 J = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(0.5, 0.5)); + mediump vec4 K = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(-1.0, 1.0)); + mediump vec4 L = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(0.0, 1.0)); + mediump vec4 M = texture2DSRGB(renderer_BlitTexture, v.v_uv + texelSize * vec2(1.0, 1.0)); + + mediump vec2 scale = vec2(0.5, 0.125); + mediump vec2 div = (1.0 / 4.0) * scale; + + mediump vec4 samplerColor = (D + E + I + J) * div.x; + samplerColor += (A + B + G + F) * div.y; + samplerColor += (B + C + H + G) * div.y; + samplerColor += (F + G + L + K) * div.y; + samplerColor += (G + H + M + L) * div.y; + #else + mediump vec4 samplerColor = texture2DSRGB(renderer_BlitTexture, v.v_uv); + #endif + + mediump vec3 color = samplerColor.rgb; + + // User controlled clamp to limit crazy high broken spec + color = min(color, HALF_MAX); + + // Thresholding + mediump float brightness = max3(color); + float threshold = material_BloomParams.x; + float thresholdKnee = material_BloomParams.y; + mediump float softness = clamp(brightness - threshold + thresholdKnee, 0.0, 2.0 * thresholdKnee); + softness = (softness * softness) / (4.0 * thresholdKnee + 1e-4); + mediump float multiplier = max(brightness - threshold, softness) / max(brightness, 1e-4); + color *= multiplier; + + // Clamp colors to positive once in prefilter. Encode can have a sqrt, and sqrt(-x) == NaN. Up/Downsample passes would then spread the NaN. + color = max(color, 0.0); + + // Bloom is addtive blend mode, we should set alpha 0 to avoid browser background color dark when canvas alpha and premultiplyAlpha is true + gl_FragColor = vec4(color, 0.0); +} + +#endif diff --git a/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomUpsample.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomUpsample.glsl new file mode 100644 index 0000000000..69c63d4542 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/PostProcess/Bloom/BloomUpsample.glsl @@ -0,0 +1,24 @@ +#ifndef BLOOM_UPSAMPLE +#define BLOOM_UPSAMPLE + +#include "PostProcess/PostCommon.glsl" +#include "PostProcess/Filtering.glsl" + +mediump sampler2D renderer_BlitTexture; +mediump sampler2D material_lowMipTexture; +vec4 material_BloomParams; +vec4 material_lowMipTexelSize; + +void frag(Varyings v) { + mediump vec4 highMip = texture2DSRGB(renderer_BlitTexture, v.v_uv); + + #ifdef BLOOM_HQ + mediump vec4 lowMip = sampleTexture2DBicubic(material_lowMipTexture, v.v_uv, material_lowMipTexelSize); + #else + mediump vec4 lowMip = texture2DSRGB(material_lowMipTexture, v.v_uv); + #endif + + gl_FragColor = mix(highMip, lowMip, material_BloomParams.z); +} + +#endif diff --git a/packages/core/src/postProcess/shaders/FXAA/FXAA3_11.glsl b/packages/shader/src/ShaderLibrary/PostProcess/FXAA/FXAA3_11.glsl similarity index 100% rename from packages/core/src/postProcess/shaders/FXAA/FXAA3_11.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/FXAA/FXAA3_11.glsl diff --git a/packages/core/src/postProcess/shaders/Filtering.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Filtering.glsl similarity index 100% rename from packages/core/src/postProcess/shaders/Filtering.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/Filtering.glsl diff --git a/packages/core/src/postProcess/shaders/FinalAntiAliasing.fs.glsl b/packages/shader/src/ShaderLibrary/PostProcess/FinalAntiAliasing.glsl similarity index 73% rename from packages/core/src/postProcess/shaders/FinalAntiAliasing.fs.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/FinalAntiAliasing.glsl index de38c0e6ad..ccddd6fcf0 100644 --- a/packages/core/src/postProcess/shaders/FinalAntiAliasing.fs.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/FinalAntiAliasing.glsl @@ -1,3 +1,6 @@ +#ifndef FINAL_ANTI_ALIASING +#define FINAL_ANTI_ALIASING + #define FXAA_PC 1 #define FXAA_QUALITY_PRESET 12 #define FXAA_GREEN_AS_LUMA 0 @@ -7,16 +10,15 @@ #define FXAA_GLSL_120 1 #endif -#include -#include +#include "Common/Common.glsl" +#include "PostProcess/FXAA/FXAA3_11.glsl" const FxaaFloat FXAA_SUBPIXEL_BLEND_AMOUNT = 0.75; const FxaaFloat FXAA_RELATIVE_CONTRAST_THRESHOLD = 0.166; const FxaaFloat FXAA_ABSOLUTE_CONTRAST_THRESHOLD = 0.0833; -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; -uniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height +sampler2D renderer_BlitTexture; +vec4 renderer_texelSize; vec4 applyFXAA(vec4 color, vec2 positionNDC, vec4 sourceSize, sampler2D blitTexture) { @@ -31,10 +33,10 @@ vec4 applyFXAA(vec4 color, vec2 positionNDC, vec4 sourceSize, sampler2D blitText ); } -void main(){ - mediump vec4 color = texture2D(renderer_BlitTexture, v_uv); +void frag(Varyings v) { + mediump vec4 color = texture2D(renderer_BlitTexture, v.v_uv); - color = applyFXAA(color, v_uv, renderer_texelSize, renderer_BlitTexture); + color = applyFXAA(color, v.v_uv, renderer_texelSize, renderer_BlitTexture); // We have convert the color to sRGB space in sRGB pass // So we need to convert it back to linear space when output to render target. @@ -45,4 +47,6 @@ void main(){ #endif gl_FragColor = color; -} \ No newline at end of file +} + +#endif diff --git a/packages/core/src/postProcess/shaders/FinalSRGB.fs.glsl b/packages/shader/src/ShaderLibrary/PostProcess/FinalSRGB.glsl similarity index 67% rename from packages/core/src/postProcess/shaders/FinalSRGB.fs.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/FinalSRGB.glsl index 60e289ef75..2fa01208cb 100644 --- a/packages/core/src/postProcess/shaders/FinalSRGB.fs.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/FinalSRGB.glsl @@ -1,17 +1,22 @@ -#include -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; +#ifndef FINAL_SRGB +#define FINAL_SRGB -void main(){ - mediump vec4 color = texture2DSRGB(renderer_BlitTexture, v_uv); +#include "Common/Common.glsl" + +mediump sampler2D renderer_BlitTexture; + +void frag(Varyings v) { + mediump vec4 color = texture2DSRGB(renderer_BlitTexture, v.v_uv); // This is final output, maybe has alpha // If we use premultiplied color to convert to sRGB. Since we ignored the background color, the greater the transparency, the greater the final composite color // But the actual transparent canvas can be composited with any color of the browser background - // So we assume non-transparent SRGB conversion. Then use the Alpha value and the background canvas to do SRGB blending + // So we assume non-transparent SRGB conversion. Then use the Alpha value and the background canvas to do SRGB blending // Although it is non-linear blending, it is more scientific color.rgb = color.rgb / color.a; color = linearToSRGB(color); gl_FragColor = vec4(color.rgb * color.a, color.a); } + +#endif diff --git a/packages/core/src/postProcess/shaders/PostCommon.glsl b/packages/shader/src/ShaderLibrary/PostProcess/PostCommon.glsl similarity index 94% rename from packages/core/src/postProcess/shaders/PostCommon.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/PostCommon.glsl index 39b650de17..e1edf1e8f5 100644 --- a/packages/core/src/postProcess/shaders/PostCommon.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/PostCommon.glsl @@ -1,7 +1,7 @@ #ifndef POST_COMMON #define POST_COMMON -#include +#include "Common/Common.glsl" #define FLT_MIN 1.175494351e-38 // Minimum normalized positive floating-point number #define HALF_MIN 6.103515625e-5 // 2^-14, the same value for 10, 11 and 16-bit: https://www.khronos.org/opengl/wiki/Small_Float_Formats #define HALF_MAX 65504.0 // (2 - 2^-10) * 2^15 diff --git a/packages/core/src/postProcess/shaders/Tonemapping/ACES/ColorTransform.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/ColorTransform.glsl similarity index 99% rename from packages/core/src/postProcess/shaders/Tonemapping/ACES/ColorTransform.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/ColorTransform.glsl index ecbd09a307..25acf34935 100644 --- a/packages/core/src/postProcess/shaders/Tonemapping/ACES/ColorTransform.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/ColorTransform.glsl @@ -3,7 +3,7 @@ // Precomputed matrices (pre-transposed) // See https://github.com/ampas/aces-dev/blob/master/transforms/ctl/README-MATRIX.md - + const mediump mat3 sRGB_2_AP0 = mat3( 0.4397010, 0.0897923, 0.0175440, 0.3829780, 0.8134230, 0.1115440, @@ -93,7 +93,7 @@ if (hue < 0.0){ hue = hue + 360.0; - } + } return hue; } @@ -104,7 +104,7 @@ hueCentered = hueCentered + 360.0; } else if (hueCentered > 180.0){ hueCentered = hueCentered - 360.0; - } + } return hueCentered; } diff --git a/packages/core/src/postProcess/shaders/Tonemapping/ACES/ODT.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/ODT.glsl similarity index 98% rename from packages/core/src/postProcess/shaders/Tonemapping/ACES/ODT.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/ODT.glsl index 5d0fabe65d..aae54c7294 100644 --- a/packages/core/src/postProcess/shaders/Tonemapping/ACES/ODT.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/ODT.glsl @@ -1,4 +1,7 @@ -#include +#ifndef ODT_GLSL +#define ODT_GLSL + +#include "PostProcess/Tonemapping/ACES/Tonescale.glsl" // Output Device Transform - RGB computer monitor @@ -127,4 +130,6 @@ mediump vec3 ODT_RGBmonitor_100nits_dim(mediump vec3 oces){ // Unity already draws to a sRGB target return linearCV; -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/packages/core/src/postProcess/shaders/Tonemapping/ACES/RRT.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/RRT.glsl similarity index 96% rename from packages/core/src/postProcess/shaders/Tonemapping/ACES/RRT.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/RRT.glsl index 388f7134fa..42127e7102 100644 --- a/packages/core/src/postProcess/shaders/Tonemapping/ACES/RRT.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/RRT.glsl @@ -1,4 +1,7 @@ -#include +#ifndef RRT_GLSL +#define RRT_GLSL + +#include "PostProcess/Tonemapping/ACES/Tonescale.glsl" // Reference Rendering Transform (RRT) @@ -75,4 +78,6 @@ mediump vec3 RRT(mediump vec3 aces){ mediump vec3 outputVal = AP1_2_AP0_MAT * rgbPost; return outputVal; -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/packages/core/src/postProcess/shaders/Tonemapping/ACES/Tonescale.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/Tonescale.glsl similarity index 99% rename from packages/core/src/postProcess/shaders/Tonemapping/ACES/Tonescale.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/Tonescale.glsl index 48af78e489..caa3e8b91f 100644 --- a/packages/core/src/postProcess/shaders/Tonemapping/ACES/Tonescale.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACES/Tonescale.glsl @@ -1,6 +1,6 @@ #ifndef TONE_SCALE #define TONE_SCALE - + const mediump mat3 M = mat3( vec3(0.5, -1.0, 0.5), vec3(-1.0, 1.0, 0.5), diff --git a/packages/core/src/postProcess/shaders/Tonemapping/ACES/ACESTonemapping.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACESTonemapping.glsl similarity index 91% rename from packages/core/src/postProcess/shaders/Tonemapping/ACES/ACESTonemapping.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACESTonemapping.glsl index c651ccb33d..f4f414d2c1 100644 --- a/packages/core/src/postProcess/shaders/Tonemapping/ACES/ACESTonemapping.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/ACESTonemapping.glsl @@ -1,10 +1,13 @@ -#include -#include -#include +#ifndef ACES_TONEMAPPING +#define ACES_TONEMAPPING + +#include "PostProcess/Tonemapping/ACES/ColorTransform.glsl" +#include "PostProcess/Tonemapping/ACES/RRT.glsl" +#include "PostProcess/Tonemapping/ACES/ODT.glsl" vec3 ACESTonemap(vec3 color){ vec3 aces = sRGB_2_AP0 * color; - + // --- Glow module --- // mediump float saturation = rgb_2_saturation(aces); mediump float ycIn = rgb_2_yc(aces); @@ -59,4 +62,6 @@ vec3 ACESTonemap(vec3 color){ return linearCV; -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/packages/core/src/postProcess/shaders/Tonemapping/NeutralTonemapping.glsl b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/NeutralTonemapping.glsl similarity index 92% rename from packages/core/src/postProcess/shaders/Tonemapping/NeutralTonemapping.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/NeutralTonemapping.glsl index 960cba909f..93f16df382 100644 --- a/packages/core/src/postProcess/shaders/Tonemapping/NeutralTonemapping.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/Tonemapping/NeutralTonemapping.glsl @@ -1,3 +1,6 @@ +#ifndef NEUTRAL_TONEMAPPING +#define NEUTRAL_TONEMAPPING + // Neutral tonemapping (Hable/Hejl/Frostbite) // Input is linear RGB // More accuracy to avoid NaN on extremely high values. @@ -25,7 +28,7 @@ vec3 neutralTonemap(vec3 color){ #endif // 1.0 / neutralCurve(whiteLevel, a, b, c, d, e, f); - const float whiteScale = 1.31338; + const float whiteScale = 1.31338; color = neutralCurve(color * whiteScale, a, b, c, d, e, f); color *= whiteScale; @@ -33,4 +36,6 @@ vec3 neutralTonemap(vec3 color){ // color /= whiteClip; return color; -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/packages/core/src/postProcess/shaders/UberPost.glsl b/packages/shader/src/ShaderLibrary/PostProcess/UberPost.glsl similarity index 54% rename from packages/core/src/postProcess/shaders/UberPost.glsl rename to packages/shader/src/ShaderLibrary/PostProcess/UberPost.glsl index 482c504231..7411507949 100644 --- a/packages/core/src/postProcess/shaders/UberPost.glsl +++ b/packages/shader/src/ShaderLibrary/PostProcess/UberPost.glsl @@ -1,35 +1,36 @@ -#include -#include -#include -#include - -varying vec2 v_uv; -uniform sampler2D renderer_BlitTexture; -uniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height +#ifndef UBER_POST +#define UBER_POST + +#include "PostProcess/PostCommon.glsl" +#include "PostProcess/Filtering.glsl" +#include "PostProcess/Tonemapping/NeutralTonemapping.glsl" +#include "PostProcess/Tonemapping/ACESTonemapping.glsl" + +mediump sampler2D renderer_BlitTexture; +vec4 renderer_texelSize; #ifdef ENABLE_EFFECT_BLOOM - uniform sampler2D material_BloomTexture; - uniform sampler2D material_BloomDirtTexture; - uniform vec4 material_BloomTint; - uniform vec4 material_BloomDirtTilingOffset; - uniform vec4 material_BloomIntensityParams; // x: bloom intensity, y: dirt intensity + mediump sampler2D material_BloomTexture; + mediump sampler2D material_BloomDirtTexture; + vec4 material_BloomTint; + vec4 material_BloomDirtTilingOffset; + vec4 material_BloomIntensityParams; #endif - -void main(){ - mediump vec4 color = texture2DSRGB(renderer_BlitTexture, v_uv); +void frag(Varyings v) { + mediump vec4 color = texture2DSRGB(renderer_BlitTexture, v.v_uv); #ifdef ENABLE_EFFECT_BLOOM #ifdef BLOOM_HQ - mediump vec4 bloom = sampleTexture2DBicubic(material_BloomTexture, v_uv, renderer_texelSize); + mediump vec4 bloom = sampleTexture2DBicubic(material_BloomTexture, v.v_uv, renderer_texelSize); #else - mediump vec4 bloom = texture2DSRGB(material_BloomTexture, v_uv); + mediump vec4 bloom = texture2DSRGB(material_BloomTexture, v.v_uv); #endif bloom *= material_BloomIntensityParams.x; color += bloom * material_BloomTint; #ifdef BLOOM_DIRT - mediump vec4 dirt = texture2DSRGB(material_BloomDirtTexture, v_uv * material_BloomDirtTilingOffset.xy + material_BloomDirtTilingOffset.zw); + mediump vec4 dirt = texture2DSRGB(material_BloomDirtTexture, v.v_uv * material_BloomDirtTilingOffset.xy + material_BloomDirtTilingOffset.zw); dirt *= material_BloomIntensityParams.y; // Additive bloom (artist friendly) color += dirt * bloom; @@ -47,4 +48,6 @@ void main(){ #endif gl_FragColor = color; -} \ No newline at end of file +} + +#endif diff --git a/packages/shader/src/shaders/Shadow.glsl b/packages/shader/src/ShaderLibrary/Shadow/Shadow.glsl similarity index 99% rename from packages/shader/src/shaders/Shadow.glsl rename to packages/shader/src/ShaderLibrary/Shadow/Shadow.glsl index 4fc3649ffd..443966a143 100644 --- a/packages/shader/src/shaders/Shadow.glsl +++ b/packages/shader/src/ShaderLibrary/Shadow/Shadow.glsl @@ -124,7 +124,7 @@ #endif #if SCENE_SHADOW_TYPE == 3 - #include "ShadowSampleTent.glsl" + #include "Shadow/ShadowSampleTent.glsl" float sampleShadowMapFiltered9(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoord, vec4 shadowmapSize) { float attenuation; diff --git a/packages/shader/src/shaders/ShadowSampleTent.glsl b/packages/shader/src/ShaderLibrary/Shadow/ShadowSampleTent.glsl similarity index 100% rename from packages/shader/src/shaders/ShadowSampleTent.glsl rename to packages/shader/src/ShaderLibrary/Shadow/ShadowSampleTent.glsl diff --git a/packages/shader/src/shaders/BlendShape.glsl b/packages/shader/src/ShaderLibrary/Skin/BlendShape.glsl similarity index 100% rename from packages/shader/src/shaders/BlendShape.glsl rename to packages/shader/src/ShaderLibrary/Skin/BlendShape.glsl diff --git a/packages/shader/src/shaders/Skin.glsl b/packages/shader/src/ShaderLibrary/Skin/Skin.glsl similarity index 100% rename from packages/shader/src/shaders/Skin.glsl rename to packages/shader/src/ShaderLibrary/Skin/Skin.glsl diff --git a/packages/shader/src/ShaderLibrary/index.ts b/packages/shader/src/ShaderLibrary/index.ts new file mode 100644 index 0000000000..50c75a8e46 --- /dev/null +++ b/packages/shader/src/ShaderLibrary/index.ts @@ -0,0 +1,164 @@ +// Common +import BlendShape from "./Skin/BlendShape.glsl"; +import Common from "./Common/Common.glsl"; +import Color from "./Common/Color.glsl"; +import Fog from "./Common/Fog.glsl"; +import Light from "./Common/Light.glsl"; +import MobileBlinnPhong from "./Common/MobileBlinnPhong.glsl"; +import Normal from "./Common/Normal.glsl"; +import Position from "./Common/Position.glsl"; +import PositionClipSpace from "./Common/PositionClipSpace.glsl"; +import Transform from "./Common/Transform.glsl"; +import UV from "./Common/UV.glsl"; +import ViewDirection from "./Common/ViewDirection.glsl"; +import WorldPosition from "./Common/WorldPosition.glsl"; +import BlitVertex from "./Common/BlitVertex.glsl"; +import Shadow from "./Shadow/Shadow.glsl"; +import ShadowSampleTent from "./Shadow/ShadowSampleTent.glsl"; +import Skin from "./Skin/Skin.glsl"; + +// PBR shading +import ForwardPassPBR from "./PBR/ForwardPassPBR.glsl"; +import AttributesPBR from "./PBR/AttributesPBR.glsl"; +import VaryingsPBR from "./PBR/VaryingsPBR.glsl"; +import FragmentPBR from "./PBR/FragmentPBR.glsl"; +import LightDirectPBR from "./PBR/LightDirectPBR.glsl"; +import LightIndirectPBR from "./PBR/LightIndirectPBR.glsl"; +import VertexPBR from "./PBR/VertexPBR.glsl"; +import LightIndirectFunctions from "./PBR/LightIndirectFunctions.glsl"; +import ReflectionLobe from "./PBR/ReflectionLobe.glsl"; +import Refraction from "./PBR/Refraction.glsl"; +import BSDF from "./PBR/BSDF.glsl"; + +// BlinnPhong +import ForwardPassBlinnPhong from "./BlinnPhong/ForwardPassBlinnPhong.glsl"; + +// Particle +import ParticleCommon from "./Particle/ParticleCommon.glsl"; +import ParticleMesh from "./Particle/ParticleMesh.glsl"; +import ParticleFeedback from "./Particle/ParticleFeedback.glsl"; +import SphereBillboard from "./Particle/Billboard/SphereBillboard.glsl"; +import StretchedBillboard from "./Particle/Billboard/StretchedBillboard.glsl"; +import VerticalBillboard from "./Particle/Billboard/VerticalBillboard.glsl"; +import HorizontalBillboard from "./Particle/Billboard/HorizontalBillboard.glsl"; +import VelocityOverLifetime from "./Particle/Module/VelocityOverLifetime.glsl"; +import RotationOverLifetime from "./Particle/Module/RotationOverLifetime.glsl"; +import SizeOverLifetime from "./Particle/Module/SizeOverLifetime.glsl"; +import ColorOverLifetime from "./Particle/Module/ColorOverLifetime.glsl"; +import TextureSheetAnimation from "./Particle/Module/TextureSheetAnimation.glsl"; +import ForceOverLifetime from "./Particle/Module/ForceOverLifetime.glsl"; +import LimitVelocityOverLifetime from "./Particle/Module/LimitVelocityOverLifetime.glsl"; +import NoiseModule from "./Particle/Module/NoiseModule.glsl"; + +// Noise +import NoiseCommon from "./Noise/NoiseCommon.glsl"; +import NoiseSimplexGrad from "./Noise/NoiseSimplexGrad.glsl"; + +// Post-process +import PostCommon from "./PostProcess/PostCommon.glsl"; +import Filtering from "./PostProcess/Filtering.glsl"; +import UberPost from "./PostProcess/UberPost.glsl"; +import BloomPrefilter from "./PostProcess/Bloom/BloomPrefilter.glsl"; +import BloomBlurH from "./PostProcess/Bloom/BloomBlurH.glsl"; +import BloomBlurV from "./PostProcess/Bloom/BloomBlurV.glsl"; +import BloomUpsample from "./PostProcess/Bloom/BloomUpsample.glsl"; +import FXAA3_11 from "./PostProcess/FXAA/FXAA3_11.glsl"; +import ACESTonemapping from "./PostProcess/Tonemapping/ACESTonemapping.glsl"; +import NeutralTonemapping from "./PostProcess/Tonemapping/NeutralTonemapping.glsl"; +import ColorTransform from "./PostProcess/Tonemapping/ACES/ColorTransform.glsl"; +import ODT from "./PostProcess/Tonemapping/ACES/ODT.glsl"; +import RRT from "./PostProcess/Tonemapping/ACES/RRT.glsl"; +import Tonescale from "./PostProcess/Tonemapping/ACES/Tonescale.glsl"; +import FinalAntiAliasing from "./PostProcess/FinalAntiAliasing.glsl"; +import FinalSRGB from "./PostProcess/FinalSRGB.glsl"; + +// AO +import ScalableAmbientOcclusion from "./AO/ScalableAmbientOcclusion.glsl"; +import BilateralBlur from "./AO/BilateralBlur.glsl"; + +interface IShaderFragment { + includeKey: string; + source: string; +} + +const fragmentList: IShaderFragment[] = [ + // Common + { source: BlendShape, includeKey: "Skin/BlendShape.glsl" }, + { source: Common, includeKey: "Common/Common.glsl" }, + { source: Color, includeKey: "Common/Color.glsl" }, + { source: Fog, includeKey: "Common/Fog.glsl" }, + { source: Light, includeKey: "Common/Light.glsl" }, + { source: MobileBlinnPhong, includeKey: "Common/MobileBlinnPhong.glsl" }, + { source: Normal, includeKey: "Common/Normal.glsl" }, + { source: Position, includeKey: "Common/Position.glsl" }, + { source: PositionClipSpace, includeKey: "Common/PositionClipSpace.glsl" }, + { source: Transform, includeKey: "Common/Transform.glsl" }, + { source: UV, includeKey: "Common/UV.glsl" }, + { source: ViewDirection, includeKey: "Common/ViewDirection.glsl" }, + { source: WorldPosition, includeKey: "Common/WorldPosition.glsl" }, + { source: BlitVertex, includeKey: "Common/BlitVertex.glsl" }, + { source: Shadow, includeKey: "Shadow/Shadow.glsl" }, + { source: ShadowSampleTent, includeKey: "Shadow/ShadowSampleTent.glsl" }, + { source: Skin, includeKey: "Skin/Skin.glsl" }, + + // PBR shading + { source: ForwardPassPBR, includeKey: "PBR/ForwardPassPBR.glsl" }, + { source: AttributesPBR, includeKey: "PBR/AttributesPBR.glsl" }, + { source: VaryingsPBR, includeKey: "PBR/VaryingsPBR.glsl" }, + { source: FragmentPBR, includeKey: "PBR/FragmentPBR.glsl" }, + { source: LightDirectPBR, includeKey: "PBR/LightDirectPBR.glsl" }, + { source: LightIndirectPBR, includeKey: "PBR/LightIndirectPBR.glsl" }, + { source: VertexPBR, includeKey: "PBR/VertexPBR.glsl" }, + { source: LightIndirectFunctions, includeKey: "PBR/LightIndirectFunctions.glsl" }, + { source: ReflectionLobe, includeKey: "PBR/ReflectionLobe.glsl" }, + { source: Refraction, includeKey: "PBR/Refraction.glsl" }, + { source: BSDF, includeKey: "PBR/BSDF.glsl" }, + + // BlinnPhong + { source: ForwardPassBlinnPhong, includeKey: "BlinnPhong/ForwardPassBlinnPhong.glsl" }, + + // Particle + { source: ParticleCommon, includeKey: "Particle/ParticleCommon.glsl" }, + { source: ParticleMesh, includeKey: "Particle/ParticleMesh.glsl" }, + { source: ParticleFeedback, includeKey: "Particle/ParticleFeedback.glsl" }, + { source: SphereBillboard, includeKey: "Particle/Billboard/SphereBillboard.glsl" }, + { source: StretchedBillboard, includeKey: "Particle/Billboard/StretchedBillboard.glsl" }, + { source: VerticalBillboard, includeKey: "Particle/Billboard/VerticalBillboard.glsl" }, + { source: HorizontalBillboard, includeKey: "Particle/Billboard/HorizontalBillboard.glsl" }, + { source: VelocityOverLifetime, includeKey: "Particle/Module/VelocityOverLifetime.glsl" }, + { source: RotationOverLifetime, includeKey: "Particle/Module/RotationOverLifetime.glsl" }, + { source: SizeOverLifetime, includeKey: "Particle/Module/SizeOverLifetime.glsl" }, + { source: ColorOverLifetime, includeKey: "Particle/Module/ColorOverLifetime.glsl" }, + { source: TextureSheetAnimation, includeKey: "Particle/Module/TextureSheetAnimation.glsl" }, + { source: ForceOverLifetime, includeKey: "Particle/Module/ForceOverLifetime.glsl" }, + { source: LimitVelocityOverLifetime, includeKey: "Particle/Module/LimitVelocityOverLifetime.glsl" }, + { source: NoiseModule, includeKey: "Particle/Module/NoiseModule.glsl" }, + + // Noise + { source: NoiseCommon, includeKey: "Noise/NoiseCommon.glsl" }, + { source: NoiseSimplexGrad, includeKey: "Noise/NoiseSimplexGrad.glsl" }, + + // Post-process + { source: PostCommon, includeKey: "PostProcess/PostCommon.glsl" }, + { source: Filtering, includeKey: "PostProcess/Filtering.glsl" }, + { source: UberPost, includeKey: "PostProcess/UberPost.glsl" }, + { source: BloomPrefilter, includeKey: "PostProcess/Bloom/BloomPrefilter.glsl" }, + { source: BloomBlurH, includeKey: "PostProcess/Bloom/BloomBlurH.glsl" }, + { source: BloomBlurV, includeKey: "PostProcess/Bloom/BloomBlurV.glsl" }, + { source: BloomUpsample, includeKey: "PostProcess/Bloom/BloomUpsample.glsl" }, + { source: FXAA3_11, includeKey: "PostProcess/FXAA/FXAA3_11.glsl" }, + { source: ACESTonemapping, includeKey: "PostProcess/Tonemapping/ACESTonemapping.glsl" }, + { source: NeutralTonemapping, includeKey: "PostProcess/Tonemapping/NeutralTonemapping.glsl" }, + { source: ColorTransform, includeKey: "PostProcess/Tonemapping/ACES/ColorTransform.glsl" }, + { source: ODT, includeKey: "PostProcess/Tonemapping/ACES/ODT.glsl" }, + { source: RRT, includeKey: "PostProcess/Tonemapping/ACES/RRT.glsl" }, + { source: Tonescale, includeKey: "PostProcess/Tonemapping/ACES/Tonescale.glsl" }, + { source: FinalAntiAliasing, includeKey: "PostProcess/FinalAntiAliasing.glsl" }, + { source: FinalSRGB, includeKey: "PostProcess/FinalSRGB.glsl" }, + + // AO + { source: ScalableAmbientOcclusion, includeKey: "AO/ScalableAmbientOcclusion.glsl" }, + { source: BilateralBlur, includeKey: "AO/BilateralBlur.glsl" } +]; + +export { fragmentList }; diff --git a/packages/shader/src/Shaders/2D/Sprite.shader b/packages/shader/src/Shaders/2D/Sprite.shader new file mode 100644 index 0000000000..8eaec4ddc4 --- /dev/null +++ b/packages/shader/src/Shaders/2D/Sprite.shader @@ -0,0 +1,39 @@ +Shader "2D/Sprite" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = SpriteVertex; + FragmentShader = SpriteFragment; + + #include "Common/Common.glsl" + + struct a2v { + vec3 POSITION; + vec2 TEXCOORD_0; + vec4 COLOR_0; + }; + + struct v2f { + vec2 v_uv; + vec4 v_color; + }; + + mat4 renderer_MVPMat; + sampler2D renderer_SpriteTexture; + + v2f SpriteVertex(a2v attr) { + v2f v; + gl_Position = renderer_MVPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + v.v_color = attr.COLOR_0; + return v; + } + + void SpriteFragment(v2f v) { + vec4 baseColor = texture2DSRGB(renderer_SpriteTexture, v.v_uv); + gl_FragColor = baseColor * v.v_color; + } + } + } +} diff --git a/packages/shader/src/Shaders/2D/SpriteMask.shader b/packages/shader/src/Shaders/2D/SpriteMask.shader new file mode 100644 index 0000000000..85959b7b38 --- /dev/null +++ b/packages/shader/src/Shaders/2D/SpriteMask.shader @@ -0,0 +1,38 @@ +Shader "2D/SpriteMask" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = SpriteMaskVertex; + FragmentShader = SpriteMaskFragment; + + struct a2v { + vec3 POSITION; + vec2 TEXCOORD_0; + }; + + struct v2f { + vec2 v_uv; + }; + + mat4 camera_VPMat; + sampler2D renderer_MaskTexture; + float renderer_MaskAlphaCutoff; + + v2f SpriteMaskVertex(a2v attr) { + v2f v; + gl_Position = camera_VPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + return v; + } + + void SpriteMaskFragment(v2f v) { + vec4 color = texture2D(renderer_MaskTexture, v.v_uv); + if (color.a < renderer_MaskAlphaCutoff) { + discard; + } + gl_FragColor = color; + } + } + } +} diff --git a/packages/shader/src/Shaders/2D/Text.shader b/packages/shader/src/Shaders/2D/Text.shader new file mode 100644 index 0000000000..419df33443 --- /dev/null +++ b/packages/shader/src/Shaders/2D/Text.shader @@ -0,0 +1,42 @@ +Shader "2D/Text" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = TextVertex; + FragmentShader = TextFragment; + + struct a2v { + vec3 POSITION; + vec2 TEXCOORD_0; + vec4 COLOR_0; + }; + + struct v2f { + vec2 v_uv; + vec4 v_color; + }; + + mat4 renderer_MVPMat; + sampler2D renderElement_TextTexture; + + v2f TextVertex(a2v attr) { + v2f v; + gl_Position = renderer_MVPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + v.v_color = attr.COLOR_0; + return v; + } + + void TextFragment(v2f v) { + vec4 texColor = texture2D(renderElement_TextTexture, v.v_uv); + #ifdef GRAPHICS_API_WEBGL2 + float coverage = texColor.r; + #else + float coverage = texColor.a; + #endif + gl_FragColor = vec4(v.v_color.rgb, v.v_color.a * coverage); + } + } + } +} diff --git a/packages/shader/src/Shaders/2D/Trail.shader b/packages/shader/src/Shaders/2D/Trail.shader new file mode 100644 index 0000000000..70fc2175de --- /dev/null +++ b/packages/shader/src/Shaders/2D/Trail.shader @@ -0,0 +1,99 @@ +Shader "2D/Trail" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = TrailVertex; + FragmentShader = TrailFragment; + + #include "Common/Common.glsl" + #include "Particle/ParticleCommon.glsl" + + struct a2v { + vec4 a_PositionBirthTime; + vec4 a_CornerTangent; + float a_Distance; + }; + + struct v2f { + vec2 v_uv; + vec4 v_color; + }; + + vec4 renderer_TrailParams; + vec2 renderer_DistanceParams; + vec3 camera_Position; + mat4 camera_ViewMat; + mat4 camera_ProjMat; + vec2 renderer_WidthCurve[4]; + vec4 renderer_ColorKeys[4]; + vec2 renderer_AlphaKeys[4]; + vec4 renderer_CurveMaxTime; + vec4 material_BaseColor; + mediump vec3 material_EmissiveColor; + + #ifdef MATERIAL_HAS_BASETEXTURE + sampler2D material_BaseTexture; + #endif + + #ifdef MATERIAL_HAS_EMISSIVETEXTURE + sampler2D material_EmissiveTexture; + #endif + + v2f TrailVertex(a2v attr) { + v2f v; + + vec3 position = attr.a_PositionBirthTime.xyz; + float corner = attr.a_CornerTangent.x; + vec3 tangent = attr.a_CornerTangent.yzw; + float distFromHead = renderer_DistanceParams.x - attr.a_Distance; + float totalDist = renderer_DistanceParams.x - renderer_DistanceParams.y; + float relativePos = totalDist > 0.0 ? distFromHead / totalDist : 0.0; + + vec3 toCamera = normalize(camera_Position - position); + vec3 right = cross(tangent, toCamera); + float rightLenSq = dot(right, right); + + if (rightLenSq < 0.000001) { + right = cross(tangent, vec3(0.0, 1.0, 0.0)); + rightLenSq = dot(right, right); + if (rightLenSq < 0.000001) { + right = cross(tangent, vec3(1.0, 0.0, 0.0)); + rightLenSq = dot(right, right); + } + } + + right = right * inversesqrt(rightLenSq); + + float width = evaluateParticleCurve(renderer_WidthCurve, min(relativePos, renderer_CurveMaxTime.z)); + vec3 worldPosition = position + right * width * 0.5 * corner; + + gl_Position = camera_ProjMat * camera_ViewMat * vec4(worldPosition, 1.0); + + float u = renderer_TrailParams.x == 0.0 ? relativePos : distFromHead; + float vCoord = corner * 0.5 + 0.5; + v.v_uv = vec2(u * renderer_TrailParams.y, vCoord * renderer_TrailParams.z); + v.v_color = evaluateParticleGradient(renderer_ColorKeys, renderer_CurveMaxTime.x, renderer_AlphaKeys, renderer_CurveMaxTime.y, relativePos); + + return v; + } + + void TrailFragment(v2f v) { + vec4 color = material_BaseColor * v.v_color; + + #ifdef MATERIAL_HAS_BASETEXTURE + color *= texture2DSRGB(material_BaseTexture, v.v_uv); + #endif + + vec3 emissiveRadiance = material_EmissiveColor; + + #ifdef MATERIAL_HAS_EMISSIVETEXTURE + emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v.v_uv).rgb; + #endif + + color.rgb += emissiveRadiance; + gl_FragColor = color; + } + } + } +} diff --git a/packages/shader/src/Shaders/2D/UIDefault.shader b/packages/shader/src/Shaders/2D/UIDefault.shader new file mode 100644 index 0000000000..331b770549 --- /dev/null +++ b/packages/shader/src/Shaders/2D/UIDefault.shader @@ -0,0 +1,47 @@ +Shader "2D/UIDefault" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + + mat4 renderer_MVPMat; + sampler2D renderer_UITexture; + + struct Attributes { + vec3 POSITION; + vec2 TEXCOORD_0; + vec4 COLOR_0; + }; + + struct Varyings { + vec2 v_uv; + vec4 v_color; + }; + + Varyings vert(Attributes attr) { + Varyings v; + + gl_Position = renderer_MVPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + v.v_color = attr.COLOR_0; + + return v; + } + + void frag(Varyings v) { + vec4 baseColor = texture2DSRGB(renderer_UITexture, v.v_uv); + vec4 finalColor = baseColor * v.v_color; + + #ifdef ENGINE_SHOULD_SRGB_CORRECT + finalColor = outputSRGBCorrection(finalColor); + #endif + + gl_FragColor = finalColor; + } + } + } +} diff --git a/packages/shader/src/Shaders/AO/ScalableAmbientOcclusion.shader b/packages/shader/src/Shaders/AO/ScalableAmbientOcclusion.shader new file mode 100644 index 0000000000..d324e8572f --- /dev/null +++ b/packages/shader/src/Shaders/AO/ScalableAmbientOcclusion.shader @@ -0,0 +1,29 @@ +Shader "AO/ScalableAmbientOcclusion" { + SubShader "Default" { + Pass "ScalableAmbientOcclusion" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "AO/ScalableAmbientOcclusion.glsl" + } + + Pass "BilateralBlur" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "AO/BilateralBlur.glsl" + } + } +} diff --git a/packages/shader/src/Shaders/BlinnPhong.shader b/packages/shader/src/Shaders/BlinnPhong.shader new file mode 100644 index 0000000000..aafec5b2b3 --- /dev/null +++ b/packages/shader/src/Shaders/BlinnPhong.shader @@ -0,0 +1,77 @@ +Shader "BlinnPhong" { + Editor { + Properties { + Header("Base") { + material_BaseColor("BaseColor", Color) = (1, 1, 1, 1); + material_BaseTexture("BaseTexture", Texture2D); + } + + Header("Emissive") { + material_EmissiveColor("EmissiveColor", Color) = (0, 0, 0, 1); + material_EmissiveTexture("EmissiveTexture", Texture2D); + } + + Header("Normal") { + material_NormalTexture("NormalTexture", Texture2D); + material_NormalIntensity("NormalIntensity", Range(0, 5, 0.01)) = 1; + } + + Header("Specular") { + material_SpecularColor("SpecularColor", Color) = (1, 1, 1, 1); + material_SpecularTexture("SpecularTexture", Texture2D); + material_Shininess("Shininess", Range(1, 1024, 1)) = 16; + } + + Header("Common") { + isTransparent("Transparent", Boolean) = false; + renderFace("Render Face", Enum(Front:0, Back:1, Double:2)) = 0; + blendMode("Blend Mode", Enum(Normal:0, Additive:1)) = 0; + material_AlphaCutoff("AlphaCutoff", Range(0, 1, 0.01)) = 0; + material_TilingOffset("TilingOffset", Vector4) = (1, 1, 0, 0); + } + } + + UIScript "UIScriptPath"; + } + + SubShader "Default" { + UsePass "Utility/ShadowMap/Default/ShadowCaster" + UsePass "Utility/DepthOnly/Default/DepthOnly" + + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + RenderQueueType renderQueueType; + BlendFactor sourceColorBlendFactor; + BlendFactor destinationColorBlendFactor; + BlendFactor sourceAlphaBlendFactor; + BlendFactor destinationAlphaBlendFactor; + CullMode rasterStateCullMode; + Bool blendEnabled; + Bool depthWriteEnabled; + + DepthState = { + WriteEnabled = depthWriteEnabled; + } + + BlendState = { + Enabled = blendEnabled; + SourceColorBlendFactor = sourceColorBlendFactor; + DestinationColorBlendFactor = destinationColorBlendFactor; + SourceAlphaBlendFactor = sourceAlphaBlendFactor; + DestinationAlphaBlendFactor = destinationAlphaBlendFactor; + } + + RasterState = { + CullMode = rasterStateCullMode; + } + + RenderQueueType = renderQueueType; + + VertexShader = BlinnPhongVertex; + FragmentShader = BlinnPhongFragment; + + #include "BlinnPhong/ForwardPassBlinnPhong.glsl" + } + } +} diff --git a/packages/shader/src/shaders/PBR.shader b/packages/shader/src/Shaders/PBR.shader similarity index 96% rename from packages/shader/src/shaders/PBR.shader rename to packages/shader/src/Shaders/PBR.shader index 7ea0b81c55..c569869702 100644 --- a/packages/shader/src/shaders/PBR.shader +++ b/packages/shader/src/Shaders/PBR.shader @@ -1,4 +1,4 @@ -Shader "PBRShaderName" { +Shader "PBR" { Editor { Properties{ Header("Base"){ @@ -89,8 +89,8 @@ Shader "PBRShaderName" { } SubShader "Default" { - UsePass "pbr/Default/ShadowCaster" - UsePass "pbr/Default/DepthOnly" + UsePass "Utility/ShadowMap/Default/ShadowCaster" + UsePass "Utility/DepthOnly/Default/DepthOnly" Pass "Forward Pass" { Tags { pipelineStage = "Forward"} @@ -125,7 +125,7 @@ Shader "PBRShaderName" { VertexShader = PBRVertex; FragmentShader = PBRFragment; - #include "ForwardPassPBR.glsl" + #include "PBR/ForwardPassPBR.glsl" } } } \ No newline at end of file diff --git a/packages/shader/src/Shaders/PBRSpecular.shader b/packages/shader/src/Shaders/PBRSpecular.shader new file mode 100644 index 0000000000..a3513b1179 --- /dev/null +++ b/packages/shader/src/Shaders/PBRSpecular.shader @@ -0,0 +1,84 @@ +Shader "PBRSpecular" { + Editor { + Properties { + Header("Base") { + material_IOR("IOR", Range(0, 5, 0.01)) = 1.5; + material_BaseColor("BaseColor", Color) = (1, 1, 1, 1); + material_BaseTexture("BaseTexture", Texture2D); + } + + Header("Specular Glossiness") { + material_SpecularColor("SpecularColor", Color) = (1, 1, 1, 1); + material_Glossiness("Glossiness", Range(0, 1, 0.01)) = 1; + material_SpecularGlossinessTexture("SpecularGlossinessTexture", Texture2D); + } + + Header("Normal") { + material_NormalTexture("NormalTexture", Texture2D); + material_NormalIntensity("NormalIntensity", Range(0, 5, 0.01)) = 1; + } + + Header("Emissive") { + material_EmissiveColor("EmissiveColor", HDRColor) = (0, 0, 0, 1); + material_EmissiveTexture("EmissiveTexture", Texture2D); + } + + Header("Occlusion") { + material_OcclusionTexture("OcclusionTexture", Texture2D); + material_OcclusionIntensity("OcclusionIntensity", Range(0, 5, 0.01)) = 1; + material_OcclusionTextureCoord("OcclusionTextureCoord", Float) = 0; + } + + Header("Common") { + isTransparent("Transparent", Boolean) = false; + renderFace("Render Face", Enum(Front:0, Back:1, Double:2)) = 0; + blendMode("Blend Mode", Enum(Normal:0, Additive:1)) = 0; + material_AlphaCutoff("AlphaCutoff", Range(0, 1, 0.01)) = 0; + material_TilingOffset("TilingOffset", Vector4) = (1, 1, 0, 0); + } + } + + UIScript "UIScriptPath"; + } + + SubShader "Default" { + UsePass "Utility/ShadowMap/Default/ShadowCaster" + UsePass "Utility/DepthOnly/Default/DepthOnly" + + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + RenderQueueType renderQueueType; + BlendFactor sourceColorBlendFactor; + BlendFactor destinationColorBlendFactor; + BlendFactor sourceAlphaBlendFactor; + BlendFactor destinationAlphaBlendFactor; + CullMode rasterStateCullMode; + Bool blendEnabled; + Bool depthWriteEnabled; + + DepthState = { + WriteEnabled = depthWriteEnabled; + } + + BlendState = { + Enabled = blendEnabled; + SourceColorBlendFactor = sourceColorBlendFactor; + DestinationColorBlendFactor = destinationColorBlendFactor; + SourceAlphaBlendFactor = sourceAlphaBlendFactor; + DestinationAlphaBlendFactor = destinationAlphaBlendFactor; + } + + RasterState = { + CullMode = rasterStateCullMode; + } + + RenderQueueType = renderQueueType; + + VertexShader = PBRVertex; + FragmentShader = PBRFragment; + + #include "PBR/ForwardPassPBR.glsl" + } + } +} diff --git a/packages/shader/src/Shaders/Particle.shader b/packages/shader/src/Shaders/Particle.shader new file mode 100644 index 0000000000..7720cdcc74 --- /dev/null +++ b/packages/shader/src/Shaders/Particle.shader @@ -0,0 +1,370 @@ +Shader "Particle" { + SubShader "Default" { + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + VertexShader = vert; + FragmentShader = frag; + + // Function-based includes + #include "Common/Common.glsl" + #include "Particle/ParticleCommon.glsl" + #include "Particle/Module/VelocityOverLifetime.glsl" + #include "Particle/Module/ForceOverLifetime.glsl" + #include "Particle/Module/ColorOverLifetime.glsl" + #include "Particle/Module/SizeOverLifetime.glsl" + #include "Particle/Module/RotationOverLifetime.glsl" + #include "Particle/Module/TextureSheetAnimation.glsl" + #include "Particle/Module/LimitVelocityOverLifetime.glsl" + + // Uniforms + float renderer_CurrentTime; + vec3 renderer_Gravity; + vec3 renderer_WorldPosition; + vec4 renderer_WorldRotation; + bool renderer_ThreeDStartRotation; + int renderer_ScalingMode; + vec3 renderer_PositionScale; + vec3 renderer_SizeScale; + vec3 renderer_PivotOffset; + + mat4 camera_ViewMat; + mat4 camera_ProjMat; + + #ifdef RENDERER_MODE_STRETCHED_BILLBOARD + vec3 camera_Position; + #endif + vec3 camera_Forward; + vec3 camera_Up; + + float renderer_StretchedBillboardLengthScale; + float renderer_StretchedBillboardSpeedScale; + int renderer_SimulationSpace; + + vec4 material_BaseColor; + mediump vec3 material_EmissiveColor; + + #ifdef MATERIAL_HAS_BASETEXTURE + sampler2D material_BaseTexture; + #endif + #ifdef MATERIAL_HAS_EMISSIVETEXTURE + sampler2D material_EmissiveTexture; + #endif + + struct Attributes { + #if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD) + vec4 a_CornerTextureCoordinate; + #endif + + #ifdef RENDERER_MODE_MESH + vec3 POSITION; + #ifdef RENDERER_ENABLE_VERTEXCOLOR + vec4 COLOR_0; + #endif + vec2 TEXCOORD_0; + #endif + + vec4 a_ShapePositionStartLifeTime; + vec4 a_DirectionTime; + vec4 a_StartColor; + vec3 a_StartSize; + vec3 a_StartRotation0; + float a_StartSpeed; + vec4 a_Random0; + + #if defined(RENDERER_TSA_FRAME_RANDOM_CURVES) || defined(RENDERER_VOL_IS_RANDOM_TWO) + vec4 a_Random1; + #endif + + #if defined(RENDERER_FOL_CONSTANT_MODE) || defined(RENDERER_FOL_CURVE_MODE) || defined(RENDERER_LVL_MODULE_ENABLED) + vec4 a_Random2; + #endif + + vec3 a_SimulationWorldPosition; + vec4 a_SimulationWorldRotation; + + #ifdef RENDERER_TRANSFORM_FEEDBACK + vec3 a_FeedbackPosition; + vec3 a_FeedbackVelocity; + #endif + + #ifdef MATERIAL_HAS_BASETEXTURE + vec4 a_SimulationUV; + #endif + }; + + struct Varyings { + vec4 v_Color; + #ifdef MATERIAL_HAS_BASETEXTURE + vec2 v_TextureCoordinate; + #endif + #ifdef RENDERER_MODE_MESH + vec4 v_MeshColor; + #endif + }; + + + vec3 computeParticlePosition(in vec3 startVelocity, in float age, in float normalizedAge, vec3 gravityVelocity, vec4 worldRotation, inout vec3 localVelocity, inout vec3 worldVelocity) { + vec3 startPosition = startVelocity * age; + vec3 finalPosition; + vec3 localPositionOffset = startPosition; + vec3 worldPositionOffset; + + #ifdef _VOL_MODULE_ENABLED + vec3 lifeVelocity; + vec3 velocityPositionOffset = computeVelocityPositionOffset(normalizedAge, age, lifeVelocity); + if (renderer_VOLSpace == 0) { + localVelocity += lifeVelocity; + localPositionOffset += velocityPositionOffset; + } else { + worldVelocity += lifeVelocity; + worldPositionOffset += velocityPositionOffset; + } + #endif + + #ifdef _FOL_MODULE_ENABLED + vec3 forceVelocity; + vec3 forcePositionOffset = computeForcePositionOffset(normalizedAge, age, forceVelocity); + if (renderer_FOLSpace == 0) { + localVelocity += forceVelocity; + localPositionOffset += forcePositionOffset; + } else { + worldVelocity += forceVelocity; + worldPositionOffset += forcePositionOffset; + } + #endif + + finalPosition = rotationByQuaternions(a_ShapePositionStartLifeTime.xyz + localPositionOffset, worldRotation) + worldPositionOffset; + + if (renderer_SimulationSpace == 0) { + finalPosition = finalPosition + renderer_WorldPosition; + } else if (renderer_SimulationSpace == 1) { + finalPosition = finalPosition + a_SimulationWorldPosition; + } + + finalPosition += 0.5 * gravityVelocity * age; + + return finalPosition; + } + + + Varyings vert(Attributes attr) { + Varyings v; + + float age = renderer_CurrentTime - a_DirectionTime.w; + float normalizedAge = age / a_ShapePositionStartLifeTime.w; + + if (normalizedAge >= 0.0 && normalizedAge < 1.0) { + vec4 worldRotation; + if (renderer_SimulationSpace == 0) { + worldRotation = renderer_WorldRotation; + } else { + worldRotation = a_SimulationWorldRotation; + } + + vec3 localVelocity; + vec3 worldVelocity; + + #ifdef RENDERER_TRANSFORM_FEEDBACK + vec3 center; + if (renderer_SimulationSpace == 0) { + center = rotationByQuaternions(a_FeedbackPosition, worldRotation) + renderer_WorldPosition; + } else if (renderer_SimulationSpace == 1) { + center = a_FeedbackPosition; + } + localVelocity = a_FeedbackVelocity; + worldVelocity = vec3(0.0); + + #ifdef _VOL_MODULE_ENABLED + vec3 instantVOLVelocity; + computeVelocityPositionOffset(normalizedAge, age, instantVOLVelocity); + if (renderer_VOLSpace == 0) { + localVelocity += instantVOLVelocity; + } else { + worldVelocity += instantVOLVelocity; + } + #endif + #else + vec3 startVelocity = a_DirectionTime.xyz * a_StartSpeed; + vec3 gravityVelocity = renderer_Gravity * a_Random0.x * age; + localVelocity = startVelocity; + worldVelocity = gravityVelocity; + vec3 center = computeParticlePosition(startVelocity, age, normalizedAge, gravityVelocity, worldRotation, localVelocity, worldVelocity); + #endif + + // Billboard / Mesh mode positioning + #ifdef RENDERER_MODE_SPHERE_BILLBOARD + vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; + vec3 sideVector = normalize(cross(camera_Forward, camera_Up)); + vec3 upVector = normalize(cross(sideVector, camera_Forward)); + corner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge); + #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE) + if (renderer_ThreeDStartRotation) { + vec3 rotation = radians(vec3(a_StartRotation0.xy, computeParticleRotationFloat(a_StartRotation0.z, age, normalizedAge))); + center += renderer_SizeScale.xzy * rotationByEuler(corner.x * sideVector + corner.y * upVector, rotation); + } else { + float rot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge)); + float c = cos(rot); + float s = sin(rot); + mat2 rotation = mat2(c, -s, s, c); + corner = rotation * corner; + center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector); + } + #else + if (renderer_ThreeDStartRotation) { + center += renderer_SizeScale.xzy * rotationByEuler(corner.x * sideVector + corner.y * upVector, radians(a_StartRotation0)); + } else { + float c = cos(radians(a_StartRotation0.x)); + float s = sin(radians(a_StartRotation0.x)); + mat2 rotation = mat2(c, -s, s, c); + corner = rotation * corner; + center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector); + } + #endif + #endif + + #ifdef RENDERER_MODE_STRETCHED_BILLBOARD + vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; + vec3 velocity = rotationByQuaternions(renderer_SizeScale * localVelocity, worldRotation) + worldVelocity; + vec3 cameraUpVector = normalize(velocity); + vec3 direction = normalize(center - camera_Position); + vec3 sideVector = normalize(cross(direction, normalize(velocity))); + + sideVector = renderer_SizeScale.xzy * sideVector; + cameraUpVector = length(vec3(renderer_SizeScale.x, 0.0, 0.0)) * cameraUpVector; + + vec2 size = computeParticleSizeBillboard(a_StartSize.xy, normalizedAge); + + const mat2 rotationZHalfPI = mat2(0.0, -1.0, 1.0, 0.0); + corner = rotationZHalfPI * corner; + corner.y = corner.y - abs(corner.y); + + float speed = length(velocity); + center += sign(renderer_SizeScale.x) * (sign(renderer_StretchedBillboardLengthScale) * size.x * corner.x * sideVector + + (speed * renderer_StretchedBillboardSpeedScale + size.y * renderer_StretchedBillboardLengthScale) * corner.y * cameraUpVector); + #endif + + #ifdef RENDERER_MODE_HORIZONTAL_BILLBOARD + vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; + const vec3 sideVector = vec3(1.0, 0.0, 0.0); + const vec3 upVector = vec3(0.0, 0.0, -1.0); + corner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge); + + float rot; + if (renderer_ThreeDStartRotation) { + rot = radians(computeParticleRotationFloat(a_StartRotation0.z, age, normalizedAge)); + } else { + rot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge)); + } + + float c = cos(rot); + float s = sin(rot); + mat2 rotation = mat2(c, -s, s, c); + corner = rotation * corner; + center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector); + #endif + + #ifdef RENDERER_MODE_VERTICAL_BILLBOARD + vec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; + const vec3 cameraUpVector = vec3(0.0, 1.0, 0.0); + vec3 sideVector = normalize(cross(camera_Forward, cameraUpVector)); + + float rot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge)); + float c = cos(rot); + float s = sin(rot); + mat2 rotation = mat2(c, -s, s, c); + corner = rotation * corner * cos(0.78539816339744830961566084581988); + corner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge); + center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * cameraUpVector); + #endif + + #ifdef RENDERER_MODE_MESH + #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE) + #define RENDERER_ROL_ENABLED + #endif + + vec3 size = computeParticleSizeMesh(a_StartSize, normalizedAge); + + bool is3DRotation = renderer_ThreeDStartRotation; + #if defined(RENDERER_ROL_ENABLED) && defined(RENDERER_ROL_IS_SEPARATE) + is3DRotation = true; + #endif + + if (is3DRotation) { + #ifdef RENDERER_ROL_ENABLED + vec3 startRotation = renderer_ThreeDStartRotation ? a_StartRotation0 : vec3(0.0, 0.0, a_StartRotation0.x); + vec3 rotation = radians(computeParticleRotationVec3(startRotation, age, normalizedAge)); + #else + vec3 rotation = radians(a_StartRotation0); + #endif + center += rotationByQuaternions(renderer_SizeScale * rotationByEuler(POSITION * size, rotation), worldRotation); + } else { + #ifdef RENDERER_ROL_ENABLED + float angle = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge)); + #else + float angle = radians(a_StartRotation0.x); + #endif + #ifdef RENDERER_EMISSION_SHAPE + vec3 axis = vec3(a_ShapePositionStartLifeTime.xy, 0.0); + if (renderer_SimulationSpace == 1) { + axis = rotationByQuaternions(axis, worldRotation); + } + vec3 crossResult = cross(axis, vec3(0.0, 0.0, -1.0)); + float crossLen = length(crossResult); + vec3 rotateAxis = crossLen > 0.0001 ? crossResult / crossLen : vec3(0.0, 1.0, 0.0); + #else + vec3 rotateAxis = vec3(0.0, 0.0, -1.0); + #endif + center += rotationByQuaternions(renderer_SizeScale * rotationByAxis(POSITION * size, rotateAxis, angle), worldRotation); + } + #ifdef RENDERER_ENABLE_VERTEXCOLOR + v.v_MeshColor = COLOR_0; + #endif + #endif + + gl_Position = camera_ProjMat * camera_ViewMat * vec4(center, 1.0); + v.v_Color = computeParticleColor(a_StartColor, normalizedAge); + + #ifdef MATERIAL_HAS_BASETEXTURE + vec2 simulateUV; + #if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD) + simulateUV = a_CornerTextureCoordinate.zw * a_SimulationUV.xy + a_SimulationUV.zw; + v.v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge); + #endif + #ifdef RENDERER_MODE_MESH + simulateUV = a_SimulationUV.zw + TEXCOORD_0 * a_SimulationUV.xy; + v.v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge); + #endif + #endif + } else { + gl_Position = vec4(2.0, 2.0, 2.0, 1.0); + } + + return v; + } + + + void frag(Varyings v) { + vec4 color = material_BaseColor * v.v_Color; + + #if defined(RENDERER_MODE_MESH) && defined(RENDERER_ENABLE_VERTEXCOLOR) + color *= v.v_MeshColor; + #endif + + #ifdef MATERIAL_HAS_BASETEXTURE + color *= texture2DSRGB(material_BaseTexture, v.v_TextureCoordinate); + #endif + + // Emissive + vec3 emissiveRadiance = material_EmissiveColor; + #ifdef MATERIAL_HAS_EMISSIVETEXTURE + emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v.v_TextureCoordinate).rgb; + #endif + + color.rgb += emissiveRadiance; + + gl_FragColor = color; + } + } + } +} diff --git a/packages/shader/src/Shaders/PostProcess/Bloom.shader b/packages/shader/src/Shaders/PostProcess/Bloom.shader new file mode 100644 index 0000000000..dff2a77414 --- /dev/null +++ b/packages/shader/src/Shaders/PostProcess/Bloom.shader @@ -0,0 +1,55 @@ +Shader "PostProcess/Bloom" { + SubShader "Default" { + Pass "Bloom Prefilter" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "PostProcess/Bloom/BloomPrefilter.glsl" + } + + Pass "Bloom Blur Horizontal" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "PostProcess/Bloom/BloomBlurH.glsl" + } + + Pass "Bloom Blur Vertical" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "PostProcess/Bloom/BloomBlurV.glsl" + } + + Pass "Bloom Upsample" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "PostProcess/Bloom/BloomUpsample.glsl" + } + } +} diff --git a/packages/shader/src/Shaders/PostProcess/FinalAntiAliasing.shader b/packages/shader/src/Shaders/PostProcess/FinalAntiAliasing.shader new file mode 100644 index 0000000000..dea4eafb74 --- /dev/null +++ b/packages/shader/src/Shaders/PostProcess/FinalAntiAliasing.shader @@ -0,0 +1,16 @@ +Shader "PostProcess/FinalAntiAliasing" { + SubShader "Default" { + Pass "0" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "PostProcess/FinalAntiAliasing.glsl" + } + } +} diff --git a/packages/shader/src/Shaders/PostProcess/FinalSRGB.shader b/packages/shader/src/Shaders/PostProcess/FinalSRGB.shader new file mode 100644 index 0000000000..586ee38e3f --- /dev/null +++ b/packages/shader/src/Shaders/PostProcess/FinalSRGB.shader @@ -0,0 +1,16 @@ +Shader "PostProcess/FinalSRGB" { + SubShader "Default" { + Pass "0" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "PostProcess/FinalSRGB.glsl" + } + } +} diff --git a/packages/shader/src/Shaders/PostProcess/Uber.shader b/packages/shader/src/Shaders/PostProcess/Uber.shader new file mode 100644 index 0000000000..8aeb890fe4 --- /dev/null +++ b/packages/shader/src/Shaders/PostProcess/Uber.shader @@ -0,0 +1,16 @@ +Shader "PostProcess/Uber" { + SubShader "Default" { + Pass "0" { + DepthState = { + Enabled = false; + WriteEnabled = false; + } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/BlitVertex.glsl" + #include "PostProcess/UberPost.glsl" + } + } +} diff --git a/packages/shader/src/Shaders/Sky/BackgroundTexture.shader b/packages/shader/src/Shaders/Sky/BackgroundTexture.shader new file mode 100644 index 0000000000..df08db200c --- /dev/null +++ b/packages/shader/src/Shaders/Sky/BackgroundTexture.shader @@ -0,0 +1,36 @@ +Shader "Sky/BackgroundTexture" { + SubShader "Default" { + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + VertexShader = BackgroundTextureVertex; + FragmentShader = BackgroundTextureFragment; + + #include "Common/Common.glsl" + + struct Attributes { + vec3 POSITION; + vec2 TEXCOORD_0; + }; + + struct Varyings { + vec2 v_uv; + }; + + vec4 camera_ProjectionParams; + sampler2D material_BaseTexture; + + Varyings BackgroundTextureVertex(Attributes attributes) { + Varyings varyings; + gl_Position = vec4(attributes.POSITION, 1.0); + gl_Position.y *= camera_ProjectionParams.x; + varyings.v_uv = attributes.TEXCOORD_0; + return varyings; + } + + void BackgroundTextureFragment(Varyings varyings) { + gl_FragColor = texture2DSRGB(material_BaseTexture, varyings.v_uv); + } + } + } +} diff --git a/packages/shader/src/Shaders/Sky/SkyProcedural.shader b/packages/shader/src/Shaders/Sky/SkyProcedural.shader new file mode 100644 index 0000000000..197682ee18 --- /dev/null +++ b/packages/shader/src/Shaders/Sky/SkyProcedural.shader @@ -0,0 +1,251 @@ +// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. +// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader) + +Shader "Sky/SkyProcedural" { + SubShader "Default" { + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + VertexShader = SkyProceduralVertex; + FragmentShader = SkyProceduralFragment; + + #include "Common/Common.glsl" + + #define OUTER_RADIUS 1.025 + #define RAYLEIGH (mix(0.0, 0.0025, pow(material_AtmosphereThickness, 2.5))) + #define MIE 0.0010 + #define SUN_BRIGHTNESS 20.0 + #define MAX_SCATTER 50.0 + + const float SKY_GROUND_THRESHOLD = 0.02; + const float outerRadius = OUTER_RADIUS; + const float outerRadius2 = OUTER_RADIUS * OUTER_RADIUS; + const float innerRadius = 1.0; + const float innerRadius2 = 1.0; + const float cameraHeight = 0.0001; + + const float HDSundiskIntensityFactor = 15.0; + const float simpleSundiskIntensityFactor = 27.0; + + const float sunScale = 400.0 * SUN_BRIGHTNESS; + const float kmESun = MIE * SUN_BRIGHTNESS; + const float km4PI = MIE * 4.0 * 3.14159265; + const float scale = 1.0 / (OUTER_RADIUS - 1.0); + const float scaleDepth = 0.25; + const float scaleOverScaleDepth = (1.0 / (OUTER_RADIUS - 1.0)) / 0.25; + const float samples = 2.0; + + const vec3 c_DefaultScatteringWavelength = vec3(0.65, 0.57, 0.475); + const vec3 c_VariableRangeForScatteringWavelength = vec3(0.15, 0.15, 0.15); + + const float MIE_G = -0.990; + const float MIE_G2 = 0.9801; + + struct Attributes { + vec4 POSITION; + }; + + struct Varyings { + vec3 v_GroundColor; + vec3 v_SkyColor; + #ifdef MATERIAL_SUN_HIGH_QUALITY + vec3 v_Vertex; + #elif defined(MATERIAL_SUN_SIMPLE) + vec3 v_RayDir; + #else + float v_SkyGroundFactor; + #endif + #if defined(MATERIAL_SUN_HIGH_QUALITY) || defined(MATERIAL_SUN_SIMPLE) + vec3 v_SunColor; + #endif + }; + + mat4 camera_VPMat; + vec3 material_SkyTint; + vec3 material_GroundTint; + float material_Exposure; + float material_AtmosphereThickness; + vec4 scene_SunlightColor; + vec3 scene_SunlightDirection; + float material_SunSize; + float material_SunSizeConvergence; + + #define GAMMA 2.2 + #define COLOR_2_GAMMA(color) pow(color, vec3(1.0 / GAMMA)) + #define COLOR_2_LINEAR(color) color + + float getRayleighPhase(vec3 light, vec3 ray) { + float eyeCos = dot(light, ray); + return 0.75 + 0.75 * eyeCos * eyeCos; + } + + float scaleAngle(float inCos) { + float x = 1.0 - inCos; + return 0.25 * exp(-0.00287 + x * (0.459 + x * (3.83 + x * (-6.80 + x * 5.25)))); + } + + float getMiePhase(float eyeCos, float eyeCos2) { + float temp = 1.0 + MIE_G2 - 2.0 * MIE_G * eyeCos; + temp = pow(temp, pow(material_SunSize, 0.65) * 10.0); + temp = max(temp, 1.0e-4); + temp = 1.5 * ((1.0 - MIE_G2) / (2.0 + MIE_G2)) * (1.0 + eyeCos2) / temp; + return temp; + } + + float calcSunAttenuation(vec3 lightPos, vec3 ray) { + #ifdef MATERIAL_SUN_HIGH_QUALITY + float focusedEyeCos = pow(clamp(dot(lightPos, ray), 0.0, 1.0), material_SunSizeConvergence); + return getMiePhase(-focusedEyeCos, focusedEyeCos * focusedEyeCos); + #else //MATERIAL_SUN_SIMPLE + vec3 delta = lightPos - ray; + float dist = length(delta); + float spot = 1.0 - smoothstep(0.0, material_SunSize, dist); + return spot * spot; + #endif + } + + Varyings SkyProceduralVertex(Attributes attributes) { + Varyings varyings; + + gl_Position = camera_VPMat * vec4(attributes.POSITION.xyz, 1.0); + + vec3 skyTintInGammaSpace = COLOR_2_GAMMA(material_SkyTint); + vec3 scatteringWavelength = mix( + c_DefaultScatteringWavelength - c_VariableRangeForScatteringWavelength, + c_DefaultScatteringWavelength + c_VariableRangeForScatteringWavelength, + vec3(1.0) - skyTintInGammaSpace + ); + vec3 invWavelength = 1.0 / pow(scatteringWavelength, vec3(4.0)); + + float krESun = RAYLEIGH * SUN_BRIGHTNESS; + float kr4PI = RAYLEIGH * 4.0 * 3.14159265; + + vec3 cameraPos = vec3(0.0, innerRadius + cameraHeight, 0.0); + + vec3 eyeRay = normalize(attributes.POSITION.xyz); + + float far = 0.0; + vec3 cIn, cOut; + if (eyeRay.y >= 0.0) { + // Sky + far = sqrt(outerRadius2 + innerRadius2 * eyeRay.y * eyeRay.y - innerRadius2) - innerRadius * eyeRay.y; + + float height = innerRadius + cameraHeight; + float depth = exp(scaleOverScaleDepth * -cameraHeight); + float startAngle = dot(eyeRay, cameraPos) / height; + float startOffset = depth * scaleAngle(startAngle); + + float sampleLength = far / samples; + float scaledLength = sampleLength * scale; + vec3 sampleRay = eyeRay * sampleLength; + vec3 samplePoint = cameraPos + sampleRay * 0.5; + + vec3 frontColor = vec3(0.0); + // Unrolled loop - iteration 1 + { + float height = length(samplePoint); + float depth = exp(scaleOverScaleDepth * (innerRadius - height)); + float lightAngle = dot(-scene_SunlightDirection, samplePoint) / height; + float cameraAngle = dot(eyeRay, samplePoint) / height; + float scatter = (startOffset + depth * (scaleAngle(lightAngle) - scaleAngle(cameraAngle))); + vec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); + + frontColor += attenuate * (depth * scaledLength); + samplePoint += sampleRay; + } + // Unrolled loop - iteration 2 + { + float height = length(samplePoint); + float depth = exp(scaleOverScaleDepth * (innerRadius - height)); + float lightAngle = dot(-scene_SunlightDirection, samplePoint) / height; + float cameraAngle = dot(eyeRay, samplePoint) / height; + float scatter = (startOffset + depth * (scaleAngle(lightAngle) - scaleAngle(cameraAngle))); + vec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); + + frontColor += attenuate * (depth * scaledLength); + samplePoint += sampleRay; + } + + cIn = frontColor * (invWavelength * krESun); + cOut = frontColor * kmESun; + } else { + // Ground + far = (-cameraHeight) / (min(-0.001, eyeRay.y)); + vec3 pos = cameraPos + far * eyeRay; + + float depth = exp((-cameraHeight) * (1.0 / scaleDepth)); + float cameraAngle = dot(-eyeRay, pos); + float lightAngle = dot(-scene_SunlightDirection, pos); + float cameraScale = scaleAngle(cameraAngle); + float lightScale = scaleAngle(lightAngle); + float cameraOffset = depth * cameraScale; + float temp = lightScale + cameraScale; + + float sampleLength = far / samples; + float scaledLength = sampleLength * scale; + vec3 sampleRay = eyeRay * sampleLength; + vec3 samplePoint = cameraPos + sampleRay * 0.5; + + vec3 frontColor = vec3(0.0, 0.0, 0.0); + vec3 attenuate; + + { + float height = length(samplePoint); + float depth = exp(scaleOverScaleDepth * (innerRadius - height)); + float scatter = depth * temp - cameraOffset; + attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); + frontColor += attenuate * (depth * scaledLength); + samplePoint += sampleRay; + } + + cIn = frontColor * (invWavelength * krESun + kmESun); + cOut = clamp(attenuate, 0.0, 1.0); + } + + #ifdef MATERIAL_SUN_HIGH_QUALITY + varyings.v_Vertex = -attributes.POSITION.xyz; + #elif defined(MATERIAL_SUN_SIMPLE) + varyings.v_RayDir = -eyeRay; + #else + varyings.v_SkyGroundFactor = -eyeRay.y / SKY_GROUND_THRESHOLD; + #endif + + varyings.v_GroundColor = material_Exposure * (cIn + COLOR_2_LINEAR(material_GroundTint) * cOut); + varyings.v_SkyColor = material_Exposure * (cIn * getRayleighPhase(-scene_SunlightDirection, -eyeRay)); + + float lightColorIntensity = clamp(length(scene_SunlightColor.xyz), 0.25, 1.0); + + #ifdef MATERIAL_SUN_HIGH_QUALITY + varyings.v_SunColor = HDSundiskIntensityFactor * clamp(cOut, 0.0, 1.0) * scene_SunlightColor.xyz / lightColorIntensity; + #elif defined(MATERIAL_SUN_SIMPLE) + varyings.v_SunColor = simpleSundiskIntensityFactor * clamp(cOut * sunScale, 0.0, 1.0) * scene_SunlightColor.xyz / lightColorIntensity; + #endif + + return varyings; + } + + void SkyProceduralFragment(Varyings varyings) { + vec3 col = vec3(0.0, 0.0, 0.0); + + #ifdef MATERIAL_SUN_HIGH_QUALITY + vec3 ray = normalize(varyings.v_Vertex); + float y = ray.y / SKY_GROUND_THRESHOLD; + #elif defined(MATERIAL_SUN_SIMPLE) + vec3 ray = varyings.v_RayDir; + float y = ray.y / SKY_GROUND_THRESHOLD; + #else + float y = varyings.v_SkyGroundFactor; + #endif + + col = mix(varyings.v_SkyColor, varyings.v_GroundColor, clamp(y, 0.0, 1.0)); + + #if defined(MATERIAL_SUN_HIGH_QUALITY) || defined(MATERIAL_SUN_SIMPLE) + if (y < 0.0) + col += varyings.v_SunColor * calcSunAttenuation(-scene_SunlightDirection, -ray); + #endif + + gl_FragColor = vec4(col, 1.0); + } + } + } +} diff --git a/packages/shader/src/Shaders/Sky/Skybox.shader b/packages/shader/src/Shaders/Sky/Skybox.shader new file mode 100644 index 0000000000..d76f44ca78 --- /dev/null +++ b/packages/shader/src/Shaders/Sky/Skybox.shader @@ -0,0 +1,51 @@ +Shader "Sky/Skybox" { + SubShader "Default" { + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + VertexShader = SkyboxVertex; + FragmentShader = SkyboxFragment; + + #include "Common/Common.glsl" + + struct Attributes { + vec3 POSITION; + }; + + struct Varyings { + vec3 v_cubeUV; + }; + + mat4 camera_VPMat; + float material_Rotation; + samplerCube material_CubeTexture; + float material_Exposure; + vec4 material_TintColor; + + vec4 rotateY(vec4 v, float angle) { + const float deg2rad = 3.1415926 / 180.0; + float radian = angle * deg2rad; + float sina = sin(radian); + float cosa = cos(radian); + mat2 m = mat2(cosa, -sina, sina, cosa); + return vec4(m * v.xz, v.yw).xzyw; + } + + Varyings SkyboxVertex(Attributes attributes) { + Varyings varyings; + varyings.v_cubeUV = attributes.POSITION; + gl_Position = camera_VPMat * rotateY(vec4(attributes.POSITION, 1.0), material_Rotation); + return varyings; + } + + void SkyboxFragment(Varyings varyings) { + vec4 textureColor = textureCube(material_CubeTexture, varyings.v_cubeUV); + #ifdef ENGINE_NO_SRGB + textureColor = sRGBToLinear(textureColor); + #endif + textureColor.rgb *= material_Exposure * material_TintColor.rgb; + gl_FragColor = textureColor; + } + } + } +} diff --git a/packages/shader/src/Shaders/Unlit.shader b/packages/shader/src/Shaders/Unlit.shader new file mode 100644 index 0000000000..84637c92a2 --- /dev/null +++ b/packages/shader/src/Shaders/Unlit.shader @@ -0,0 +1,208 @@ +Shader "Unlit" { + Editor { + Properties { + Header("Base") { + material_BaseColor("BaseColor", Color) = (1, 1, 1, 1); + material_BaseTexture("BaseTexture", Texture2D); + } + + Header("Common") { + isTransparent("Transparent", Boolean) = false; + renderFace("Render Face", Enum(Front:0, Back:1, Double:2)) = 0; + blendMode("Blend Mode", Enum(Normal:0, Additive:1)) = 0; + material_AlphaCutoff("AlphaCutoff", Range(0, 1, 0.01)) = 0; + material_TilingOffset("TilingOffset", Vector4) = (1, 1, 0, 0); + } + } + + UIScript "UIScriptPath"; + } + + SubShader "Default" { + UsePass "Utility/ShadowMap/Default/ShadowCaster" + UsePass "Utility/DepthOnly/Default/DepthOnly" + + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + RenderQueueType renderQueueType; + BlendFactor sourceColorBlendFactor; + BlendFactor destinationColorBlendFactor; + BlendFactor sourceAlphaBlendFactor; + BlendFactor destinationAlphaBlendFactor; + CullMode rasterStateCullMode; + Bool blendEnabled; + Bool depthWriteEnabled; + + DepthState = { + WriteEnabled = depthWriteEnabled; + } + + BlendState = { + Enabled = blendEnabled; + SourceColorBlendFactor = sourceColorBlendFactor; + DestinationColorBlendFactor = destinationColorBlendFactor; + SourceAlphaBlendFactor = sourceAlphaBlendFactor; + DestinationAlphaBlendFactor = destinationAlphaBlendFactor; + } + + RasterState = { + CullMode = rasterStateCullMode; + } + + RenderQueueType = renderQueueType; + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + #include "Common/Transform.glsl" + #include "Common/Fog.glsl" + #include "Skin/Skin.glsl" + #include "Skin/BlendShape.glsl" + + vec4 material_TilingOffset; + vec4 material_BaseColor; + float material_AlphaCutoff; + + #ifdef MATERIAL_HAS_BASETEXTURE + sampler2D material_BaseTexture; + #endif + + struct Attributes { + vec3 POSITION; + + #ifdef RENDERER_HAS_BLENDSHAPE + #ifndef RENDERER_BLENDSHAPE_USE_TEXTURE + vec3 POSITION_BS0; + vec3 POSITION_BS1; + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) && defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + #else + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) || defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 POSITION_BS2; + vec3 POSITION_BS3; + #ifdef RENDERER_BLENDSHAPE_HAS_NORMAL + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 NORMAL_BS2; + vec3 NORMAL_BS3; + #endif + #ifdef RENDERER_BLENDSHAPE_HAS_TANGENT + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + vec3 TANGENT_BS2; + vec3 TANGENT_BS3; + #endif + #else + vec3 POSITION_BS2; + vec3 POSITION_BS3; + vec3 POSITION_BS4; + vec3 POSITION_BS5; + vec3 POSITION_BS6; + vec3 POSITION_BS7; + #endif + #endif + #endif + #endif + + #ifdef RENDERER_HAS_UV + vec2 TEXCOORD_0; + #endif + + #ifdef RENDERER_HAS_SKIN + vec4 JOINTS_0; + vec4 WEIGHTS_0; + #endif + + #ifdef RENDERER_HAS_NORMAL + vec3 NORMAL; + #endif + + #ifdef RENDERER_HAS_TANGENT + vec4 TANGENT; + #endif + }; + + struct Varyings { + vec2 v_uv; + #if SCENE_FOG_MODE != 0 + vec3 v_positionVS; + #endif + }; + + Varyings vert(Attributes attr) { + Varyings v; + + vec4 position = vec4(attr.POSITION, 1.0); + + #ifdef RENDERER_HAS_NORMAL + vec3 normal = attr.NORMAL; + #ifdef RENDERER_HAS_TANGENT + vec4 tangent = attr.TANGENT; + #endif + #endif + + #ifdef RENDERER_HAS_BLENDSHAPE + calculateBlendShape(attr, position + #ifdef RENDERER_HAS_NORMAL + , normal + #ifdef RENDERER_HAS_TANGENT + , tangent + #endif + #endif + ); + #endif + + #ifdef RENDERER_HAS_SKIN + mat4 skinMatrix = getSkinMatrix(attr); + position = skinMatrix * position; + #endif + + #ifdef RENDERER_HAS_UV + v.v_uv = attr.TEXCOORD_0; + #else + v.v_uv = vec2(0.0); + #endif + #ifdef MATERIAL_NEED_TILING_OFFSET + v.v_uv = v.v_uv * material_TilingOffset.xy + material_TilingOffset.zw; + #endif + + gl_Position = renderer_MVPMat * position; + + #if SCENE_FOG_MODE != 0 + v.v_positionVS = (renderer_MVMat * position).xyz; + #endif + + return v; + } + + void frag(Varyings v) { + vec4 baseColor = material_BaseColor; + + #ifdef MATERIAL_HAS_BASETEXTURE + baseColor *= texture2DSRGB(material_BaseTexture, v.v_uv); + #endif + + #ifdef MATERIAL_IS_ALPHA_CUTOFF + if (baseColor.a < material_AlphaCutoff) { + discard; + } + #endif + + gl_FragColor = baseColor; + + #ifndef MATERIAL_IS_TRANSPARENT + gl_FragColor.a = 1.0; + #endif + + #if SCENE_FOG_MODE != 0 + gl_FragColor = fog(gl_FragColor, v.v_positionVS); + #endif + } + } + } +} diff --git a/packages/shader/src/Shaders/Utility/Blit.shader b/packages/shader/src/Shaders/Utility/Blit.shader new file mode 100644 index 0000000000..6e7469f4d7 --- /dev/null +++ b/packages/shader/src/Shaders/Utility/Blit.shader @@ -0,0 +1,54 @@ +Shader "Utility/Blit" { + SubShader "Default" { + Pass "Forward" { + Tags { pipelineStage = "Forward" } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + + mediump sampler2D renderer_BlitTexture; + #ifdef HAS_TEX_LOD + float renderer_BlitMipLevel; + #endif + vec4 renderer_SourceScaleOffset; + + struct Attributes { + vec4 POSITION_UV; + }; + + struct Varyings { + vec2 v_uv; + }; + + Varyings vert(Attributes attr) { + Varyings v; + gl_Position = vec4(attr.POSITION_UV.xy, 0.0, 1.0); + v.v_uv = attr.POSITION_UV.zw; + return v; + } + + #ifdef HAS_TEX_LOD + vec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) { + vec4 color = texture2DLodEXT(tex, uv, lod); + #ifdef ENGINE_NO_SRGB + color = sRGBToLinear(color); + #endif + return color; + } + #endif + + void frag(Varyings v) { + vec2 uv = v.v_uv; + uv = uv * renderer_SourceScaleOffset.xy + renderer_SourceScaleOffset.zw; + + #ifdef HAS_TEX_LOD + gl_FragColor = texture2DLodSRGB(renderer_BlitTexture, uv, renderer_BlitMipLevel); + #else + gl_FragColor = texture2DSRGB(renderer_BlitTexture, uv); + #endif + } + } + } +} diff --git a/packages/shader/src/Shaders/Utility/BlitScreen.shader b/packages/shader/src/Shaders/Utility/BlitScreen.shader new file mode 100644 index 0000000000..ff98b60d72 --- /dev/null +++ b/packages/shader/src/Shaders/Utility/BlitScreen.shader @@ -0,0 +1,57 @@ +Shader "Utility/BlitScreen" { + SubShader "Default" { + Pass "Forward" { + Tags { pipelineStage = "Forward" } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + + mediump sampler2D renderer_BlitTexture; + #ifdef HAS_TEX_LOD + float renderer_BlitMipLevel; + #endif + + struct Attributes { + vec4 POSITION_UV; + }; + + struct Varyings { + vec2 v_uv; + }; + + Varyings vert(Attributes attr) { + Varyings v; + gl_Position = vec4(attr.POSITION_UV.xy, 0.0, 1.0); + v.v_uv = attr.POSITION_UV.zw; + return v; + } + + #ifdef HAS_TEX_LOD + vec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) { + vec4 color = texture2DLodEXT(tex, uv, lod); + #ifdef ENGINE_NO_SRGB + color = sRGBToLinear(color); + #endif + return color; + } + #endif + + void frag(Varyings v) { + vec2 uv = v.v_uv; + // Screen uv is flipped + uv.y = 1.0 - uv.y; + + #ifdef HAS_TEX_LOD + gl_FragColor = texture2DLodSRGB(renderer_BlitTexture, uv, renderer_BlitMipLevel); + #else + gl_FragColor = texture2D(renderer_BlitTexture, uv); + #endif + + // Color space in screen is in gamma space but without sRGB texture, so convert to linear space + gl_FragColor = sRGBToLinear(gl_FragColor); + } + } + } +} diff --git a/packages/shader/src/Shaders/Utility/DepthOnly.shader b/packages/shader/src/Shaders/Utility/DepthOnly.shader new file mode 100644 index 0000000000..ad11efe8d4 --- /dev/null +++ b/packages/shader/src/Shaders/Utility/DepthOnly.shader @@ -0,0 +1,113 @@ +Shader "Utility/DepthOnly" { + SubShader "Default" { + Pass "DepthOnly" { + Tags { pipelineStage = "DepthOnly" } + + RenderQueueType = material_DepthOnlyRenderQueue; + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + #include "Common/Transform.glsl" + #include "Skin/Skin.glsl" + #include "Skin/BlendShape.glsl" + + mat4 camera_VPMat; + + struct Attributes { + vec3 POSITION; + + #ifdef RENDERER_HAS_BLENDSHAPE + #ifndef RENDERER_BLENDSHAPE_USE_TEXTURE + vec3 POSITION_BS0; + vec3 POSITION_BS1; + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) && defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + #else + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) || defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 POSITION_BS2; + vec3 POSITION_BS3; + #ifdef RENDERER_BLENDSHAPE_HAS_NORMAL + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 NORMAL_BS2; + vec3 NORMAL_BS3; + #endif + #ifdef RENDERER_BLENDSHAPE_HAS_TANGENT + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + vec3 TANGENT_BS2; + vec3 TANGENT_BS3; + #endif + #else + vec3 POSITION_BS2; + vec3 POSITION_BS3; + vec3 POSITION_BS4; + vec3 POSITION_BS5; + vec3 POSITION_BS6; + vec3 POSITION_BS7; + #endif + #endif + #endif + #endif + + #ifdef RENDERER_HAS_SKIN + vec4 JOINTS_0; + vec4 WEIGHTS_0; + #endif + + #ifdef RENDERER_HAS_NORMAL + vec3 NORMAL; + #endif + + #ifdef RENDERER_HAS_TANGENT + vec4 TANGENT; + #endif + }; + + struct Varyings { + float _placeholder; + }; + + Varyings vert(Attributes attr) { + Varyings v; + + vec4 position = vec4(attr.POSITION, 1.0); + + #ifdef RENDERER_HAS_NORMAL + vec3 normal = vec3(attr.NORMAL); + #ifdef RENDERER_HAS_TANGENT + vec4 tangent = vec4(attr.TANGENT); + #endif + #endif + + #ifdef RENDERER_HAS_BLENDSHAPE + calculateBlendShape(attr, position + #ifdef RENDERER_HAS_NORMAL + , normal + #ifdef RENDERER_HAS_TANGENT + , tangent + #endif + #endif + ); + #endif + + #ifdef RENDERER_HAS_SKIN + mat4 skinMatrix = getSkinMatrix(attr); + position = skinMatrix * position; + #endif + + gl_Position = camera_VPMat * renderer_ModelMat * position; + + return v; + } + + void frag(Varyings v) { + } + } + } +} diff --git a/packages/shader/src/Shaders/Utility/ShadowMap.shader b/packages/shader/src/Shaders/Utility/ShadowMap.shader new file mode 100644 index 0000000000..3599cf96d8 --- /dev/null +++ b/packages/shader/src/Shaders/Utility/ShadowMap.shader @@ -0,0 +1,189 @@ +Shader "Utility/ShadowMap" { + SubShader "Default" { + Pass "ShadowCaster" { + Tags { pipelineStage = "ShadowCaster" } + + RenderQueueType = material_ShadowCasterRenderQueue; + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + #include "Common/Transform.glsl" + #include "Skin/Skin.glsl" + #include "Skin/BlendShape.glsl" + + mat4 camera_VPMat; + vec2 scene_ShadowBias; + vec3 scene_LightDirection; + + vec4 material_BaseColor; + sampler2D material_BaseTexture; + float material_AlphaCutoff; + + struct Attributes { + vec3 POSITION; + + #ifdef RENDERER_HAS_BLENDSHAPE + #ifndef RENDERER_BLENDSHAPE_USE_TEXTURE + vec3 POSITION_BS0; + vec3 POSITION_BS1; + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) && defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + #else + #if defined(RENDERER_BLENDSHAPE_HAS_NORMAL) || defined(RENDERER_BLENDSHAPE_HAS_TANGENT) + vec3 POSITION_BS2; + vec3 POSITION_BS3; + #ifdef RENDERER_BLENDSHAPE_HAS_NORMAL + vec3 NORMAL_BS0; + vec3 NORMAL_BS1; + vec3 NORMAL_BS2; + vec3 NORMAL_BS3; + #endif + #ifdef RENDERER_BLENDSHAPE_HAS_TANGENT + vec3 TANGENT_BS0; + vec3 TANGENT_BS1; + vec3 TANGENT_BS2; + vec3 TANGENT_BS3; + #endif + #else + vec3 POSITION_BS2; + vec3 POSITION_BS3; + vec3 POSITION_BS4; + vec3 POSITION_BS5; + vec3 POSITION_BS6; + vec3 POSITION_BS7; + #endif + #endif + #endif + #endif + + #ifdef RENDERER_HAS_SKIN + vec4 JOINTS_0; + vec4 WEIGHTS_0; + #endif + + #ifdef RENDERER_HAS_NORMAL + vec3 NORMAL; + #endif + + #ifdef RENDERER_HAS_TANGENT + vec4 TANGENT; + #endif + + #ifdef RENDERER_HAS_UV + vec2 TEXCOORD_0; + #endif + }; + + struct Varyings { + vec2 v_uv; + }; + + vec3 applyShadowBias(vec3 positionWS) { + positionWS -= scene_LightDirection * scene_ShadowBias.x; + return positionWS; + } + + vec3 applyShadowNormalBias(vec3 positionWS, vec3 normalWS) { + float invNdotL = 1.0 - clamp(dot(-scene_LightDirection, normalWS), 0.0, 1.0); + float scale = invNdotL * scene_ShadowBias.y; + positionWS += normalWS * vec3(scale); + return positionWS; + } + + Varyings vert(Attributes attr) { + Varyings v; + + vec4 position = vec4(attr.POSITION, 1.0); + + #ifdef RENDERER_HAS_NORMAL + vec3 normal = vec3(attr.NORMAL); + #ifdef RENDERER_HAS_TANGENT + vec4 tangent = vec4(attr.TANGENT); + #endif + #endif + + #ifdef RENDERER_HAS_BLENDSHAPE + calculateBlendShape(attr, position + #ifdef RENDERER_HAS_NORMAL + , normal + #ifdef RENDERER_HAS_TANGENT + , tangent + #endif + #endif + ); + #endif + + #ifdef RENDERER_HAS_SKIN + mat4 skinMatrix = getSkinMatrix(attr); + position = skinMatrix * position; + + #ifdef RENDERER_HAS_NORMAL + mat3 skinNormalMatrix = INVERSE_MAT(mat3(skinMatrix)); + normal = normal * skinNormalMatrix; + #endif + #endif + + #ifdef RENDERER_HAS_UV + v.v_uv = attr.TEXCOORD_0; + #else + v.v_uv = vec2(0.0, 0.0); + #endif + + vec4 positionWS = renderer_ModelMat * position; + + positionWS.xyz = applyShadowBias(positionWS.xyz); + #ifdef RENDERER_HAS_NORMAL + vec3 normalWS = normalize(mat3(renderer_NormalMat) * normal); + positionWS.xyz = applyShadowNormalBias(positionWS.xyz, normalWS); + #endif + + vec4 positionCS = camera_VPMat * positionWS; + positionCS.z = max(positionCS.z, -1.0); + gl_Position = positionCS; + + return v; + } + + #ifdef ENGINE_NO_DEPTH_TEXTURE + vec4 pack(float depth) { + const vec4 bitShift = vec4(1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0); + const vec4 bitMask = vec4(1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0, 0.0); + vec4 rgbaDepth = fract(depth * bitShift); + rgbaDepth -= rgbaDepth.gbaa * bitMask; + return rgbaDepth; + } + #endif + + void frag(Varyings v) { + #if defined(MATERIAL_IS_ALPHA_CUTOFF) || (defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT)) + float alpha = material_BaseColor.a; + #ifdef MATERIAL_HAS_BASETEXTURE + alpha *= texture2D(material_BaseTexture, v.v_uv).a; + #endif + #ifdef MATERIAL_IS_ALPHA_CUTOFF + if (alpha < material_AlphaCutoff) { + discard; + } + #endif + #if defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT) + float noise = fract(52.982919 * fract(dot(vec2(0.06711, 0.00584), gl_FragCoord.xy))); + if (alpha <= noise) { + discard; + } + #endif + #endif + + #ifdef ENGINE_NO_DEPTH_TEXTURE + gl_FragColor = pack(gl_FragCoord.z); + #else + gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); + #endif + } + } + } +} diff --git a/packages/shader/src/Shaders/index.ts b/packages/shader/src/Shaders/index.ts new file mode 100644 index 0000000000..ce558bf229 --- /dev/null +++ b/packages/shader/src/Shaders/index.ts @@ -0,0 +1,60 @@ +// Material shaders +import PBRSource from "./PBR.shader"; +import PBRSpecularSource from "./PBRSpecular.shader"; +import BlinnPhongSource from "./BlinnPhong.shader"; +import UnlitSource from "./Unlit.shader"; + +// 2D shaders +import SpriteSource from "./2D/Sprite.shader"; +import SpriteMaskSource from "./2D/SpriteMask.shader"; +import TextSource from "./2D/Text.shader"; +import TrailSource from "./2D/Trail.shader"; +import UIDefaultSource from "./2D/UIDefault.shader"; + +// Sky shaders +import SkyboxSource from "./Sky/Skybox.shader"; +import BackgroundTextureSource from "./Sky/BackgroundTexture.shader"; +import SkyProceduralSource from "./Sky/SkyProcedural.shader"; + +// Utility shaders +import DepthOnlySource from "./Utility/DepthOnly.shader"; +import ShadowMapSource from "./Utility/ShadowMap.shader"; +import BlitSource from "./Utility/Blit.shader"; +import BlitScreenSource from "./Utility/BlitScreen.shader"; + +// Particle shader +import ParticleSource from "./Particle.shader"; + +// PostProcess shaders +import UberShaderSource from "./PostProcess/Uber.shader"; +import FinalSRGBShaderSource from "./PostProcess/FinalSRGB.shader"; +import FinalAntiAliasingShaderSource from "./PostProcess/FinalAntiAliasing.shader"; +import BloomShaderSource from "./PostProcess/Bloom.shader"; + +// AO shader +import SAOShaderSource from "./AO/ScalableAmbientOcclusion.shader"; + +export { + PBRSource, + PBRSpecularSource, + BlinnPhongSource, + UnlitSource, + SpriteSource, + SpriteMaskSource, + TextSource, + TrailSource, + UIDefaultSource, + SkyboxSource, + BackgroundTextureSource, + SkyProceduralSource, + DepthOnlySource, + ShadowMapSource, + BlitSource, + BlitScreenSource, + ParticleSource, + UberShaderSource, + FinalSRGBShaderSource, + FinalAntiAliasingShaderSource, + BloomShaderSource, + SAOShaderSource +}; diff --git a/packages/shader/src/index.ts b/packages/shader/src/index.ts index 52e67499c6..3882af7a5e 100644 --- a/packages/shader/src/index.ts +++ b/packages/shader/src/index.ts @@ -1,16 +1,25 @@ -import { ShaderFactory } from "@galacean/engine"; -import { PBRSource, fragmentList } from "./shaders"; - -let includeRegistered = false; - -export function registerIncludes() { - if (includeRegistered) return; - - for (const sourceFragment of fragmentList) { - ShaderFactory.registerInclude(sourceFragment.includeKey, sourceFragment.source); - } - - includeRegistered = true; -} - -export { PBRSource, fragmentList }; +export { fragmentList } from "./ShaderLibrary"; +export { + PBRSource, + PBRSpecularSource, + BlinnPhongSource, + UnlitSource, + SpriteSource, + SpriteMaskSource, + TextSource, + TrailSource, + UIDefaultSource, + SkyboxSource, + BackgroundTextureSource, + SkyProceduralSource, + DepthOnlySource, + ShadowMapSource, + BlitSource, + BlitScreenSource, + ParticleSource, + UberShaderSource, + FinalSRGBShaderSource, + FinalAntiAliasingShaderSource, + BloomShaderSource, + SAOShaderSource +} from "./Shaders"; diff --git a/packages/shader/src/shaders/2d/Sprite.shader b/packages/shader/src/shaders/2d/Sprite.shader new file mode 100644 index 0000000000..8eaec4ddc4 --- /dev/null +++ b/packages/shader/src/shaders/2d/Sprite.shader @@ -0,0 +1,39 @@ +Shader "2D/Sprite" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = SpriteVertex; + FragmentShader = SpriteFragment; + + #include "Common/Common.glsl" + + struct a2v { + vec3 POSITION; + vec2 TEXCOORD_0; + vec4 COLOR_0; + }; + + struct v2f { + vec2 v_uv; + vec4 v_color; + }; + + mat4 renderer_MVPMat; + sampler2D renderer_SpriteTexture; + + v2f SpriteVertex(a2v attr) { + v2f v; + gl_Position = renderer_MVPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + v.v_color = attr.COLOR_0; + return v; + } + + void SpriteFragment(v2f v) { + vec4 baseColor = texture2DSRGB(renderer_SpriteTexture, v.v_uv); + gl_FragColor = baseColor * v.v_color; + } + } + } +} diff --git a/packages/shader/src/shaders/2d/SpriteMask.shader b/packages/shader/src/shaders/2d/SpriteMask.shader new file mode 100644 index 0000000000..85959b7b38 --- /dev/null +++ b/packages/shader/src/shaders/2d/SpriteMask.shader @@ -0,0 +1,38 @@ +Shader "2D/SpriteMask" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = SpriteMaskVertex; + FragmentShader = SpriteMaskFragment; + + struct a2v { + vec3 POSITION; + vec2 TEXCOORD_0; + }; + + struct v2f { + vec2 v_uv; + }; + + mat4 camera_VPMat; + sampler2D renderer_MaskTexture; + float renderer_MaskAlphaCutoff; + + v2f SpriteMaskVertex(a2v attr) { + v2f v; + gl_Position = camera_VPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + return v; + } + + void SpriteMaskFragment(v2f v) { + vec4 color = texture2D(renderer_MaskTexture, v.v_uv); + if (color.a < renderer_MaskAlphaCutoff) { + discard; + } + gl_FragColor = color; + } + } + } +} diff --git a/packages/shader/src/shaders/2d/Text.shader b/packages/shader/src/shaders/2d/Text.shader new file mode 100644 index 0000000000..419df33443 --- /dev/null +++ b/packages/shader/src/shaders/2d/Text.shader @@ -0,0 +1,42 @@ +Shader "2D/Text" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = TextVertex; + FragmentShader = TextFragment; + + struct a2v { + vec3 POSITION; + vec2 TEXCOORD_0; + vec4 COLOR_0; + }; + + struct v2f { + vec2 v_uv; + vec4 v_color; + }; + + mat4 renderer_MVPMat; + sampler2D renderElement_TextTexture; + + v2f TextVertex(a2v attr) { + v2f v; + gl_Position = renderer_MVPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + v.v_color = attr.COLOR_0; + return v; + } + + void TextFragment(v2f v) { + vec4 texColor = texture2D(renderElement_TextTexture, v.v_uv); + #ifdef GRAPHICS_API_WEBGL2 + float coverage = texColor.r; + #else + float coverage = texColor.a; + #endif + gl_FragColor = vec4(v.v_color.rgb, v.v_color.a * coverage); + } + } + } +} diff --git a/packages/shader/src/shaders/2d/Trail.shader b/packages/shader/src/shaders/2d/Trail.shader new file mode 100644 index 0000000000..70fc2175de --- /dev/null +++ b/packages/shader/src/shaders/2d/Trail.shader @@ -0,0 +1,99 @@ +Shader "2D/Trail" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = TrailVertex; + FragmentShader = TrailFragment; + + #include "Common/Common.glsl" + #include "Particle/ParticleCommon.glsl" + + struct a2v { + vec4 a_PositionBirthTime; + vec4 a_CornerTangent; + float a_Distance; + }; + + struct v2f { + vec2 v_uv; + vec4 v_color; + }; + + vec4 renderer_TrailParams; + vec2 renderer_DistanceParams; + vec3 camera_Position; + mat4 camera_ViewMat; + mat4 camera_ProjMat; + vec2 renderer_WidthCurve[4]; + vec4 renderer_ColorKeys[4]; + vec2 renderer_AlphaKeys[4]; + vec4 renderer_CurveMaxTime; + vec4 material_BaseColor; + mediump vec3 material_EmissiveColor; + + #ifdef MATERIAL_HAS_BASETEXTURE + sampler2D material_BaseTexture; + #endif + + #ifdef MATERIAL_HAS_EMISSIVETEXTURE + sampler2D material_EmissiveTexture; + #endif + + v2f TrailVertex(a2v attr) { + v2f v; + + vec3 position = attr.a_PositionBirthTime.xyz; + float corner = attr.a_CornerTangent.x; + vec3 tangent = attr.a_CornerTangent.yzw; + float distFromHead = renderer_DistanceParams.x - attr.a_Distance; + float totalDist = renderer_DistanceParams.x - renderer_DistanceParams.y; + float relativePos = totalDist > 0.0 ? distFromHead / totalDist : 0.0; + + vec3 toCamera = normalize(camera_Position - position); + vec3 right = cross(tangent, toCamera); + float rightLenSq = dot(right, right); + + if (rightLenSq < 0.000001) { + right = cross(tangent, vec3(0.0, 1.0, 0.0)); + rightLenSq = dot(right, right); + if (rightLenSq < 0.000001) { + right = cross(tangent, vec3(1.0, 0.0, 0.0)); + rightLenSq = dot(right, right); + } + } + + right = right * inversesqrt(rightLenSq); + + float width = evaluateParticleCurve(renderer_WidthCurve, min(relativePos, renderer_CurveMaxTime.z)); + vec3 worldPosition = position + right * width * 0.5 * corner; + + gl_Position = camera_ProjMat * camera_ViewMat * vec4(worldPosition, 1.0); + + float u = renderer_TrailParams.x == 0.0 ? relativePos : distFromHead; + float vCoord = corner * 0.5 + 0.5; + v.v_uv = vec2(u * renderer_TrailParams.y, vCoord * renderer_TrailParams.z); + v.v_color = evaluateParticleGradient(renderer_ColorKeys, renderer_CurveMaxTime.x, renderer_AlphaKeys, renderer_CurveMaxTime.y, relativePos); + + return v; + } + + void TrailFragment(v2f v) { + vec4 color = material_BaseColor * v.v_color; + + #ifdef MATERIAL_HAS_BASETEXTURE + color *= texture2DSRGB(material_BaseTexture, v.v_uv); + #endif + + vec3 emissiveRadiance = material_EmissiveColor; + + #ifdef MATERIAL_HAS_EMISSIVETEXTURE + emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v.v_uv).rgb; + #endif + + color.rgb += emissiveRadiance; + gl_FragColor = color; + } + } + } +} diff --git a/packages/shader/src/shaders/2d/UIDefault.shader b/packages/shader/src/shaders/2d/UIDefault.shader new file mode 100644 index 0000000000..331b770549 --- /dev/null +++ b/packages/shader/src/shaders/2d/UIDefault.shader @@ -0,0 +1,47 @@ +Shader "2D/UIDefault" { + SubShader "Default" { + Pass "Default" { + Tags { pipelineStage = "Forward" } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + + mat4 renderer_MVPMat; + sampler2D renderer_UITexture; + + struct Attributes { + vec3 POSITION; + vec2 TEXCOORD_0; + vec4 COLOR_0; + }; + + struct Varyings { + vec2 v_uv; + vec4 v_color; + }; + + Varyings vert(Attributes attr) { + Varyings v; + + gl_Position = renderer_MVPMat * vec4(attr.POSITION, 1.0); + v.v_uv = attr.TEXCOORD_0; + v.v_color = attr.COLOR_0; + + return v; + } + + void frag(Varyings v) { + vec4 baseColor = texture2DSRGB(renderer_UITexture, v.v_uv); + vec4 finalColor = baseColor * v.v_color; + + #ifdef ENGINE_SHOULD_SRGB_CORRECT + finalColor = outputSRGBCorrection(finalColor); + #endif + + gl_FragColor = finalColor; + } + } + } +} diff --git a/packages/shader/src/shaders/index.ts b/packages/shader/src/shaders/index.ts deleted file mode 100644 index 3a0430c975..0000000000 --- a/packages/shader/src/shaders/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -import BlendShape from "./BlendShape.glsl"; -import Common from "./Common.glsl"; -import Fog from "./Fog.glsl"; -import Light from "./Light.glsl"; -import Normal from "./Normal.glsl"; -import PBRSource from "./PBR.shader"; -import Shadow from "./Shadow.glsl"; -import ShadowSampleTent from "./ShadowSampleTent.glsl"; -import Skin from "./Skin.glsl"; -import Transform from "./Transform.glsl"; -import shadingPBR from "./shadingPBR"; - -interface IShaderFragment { - includeKey: string; - source: string; -} - -const fragmentList: IShaderFragment[] = [ - { source: BlendShape, includeKey: "BlendShape.glsl" }, - { source: Common, includeKey: "Common.glsl" }, - { source: Fog, includeKey: "Fog.glsl" }, - { source: Light, includeKey: "Light.glsl" }, - { source: Normal, includeKey: "Normal.glsl" }, - { source: ShadowSampleTent, includeKey: "ShadowSampleTent.glsl" }, - { source: Shadow, includeKey: "Shadow.glsl" }, - { source: Transform, includeKey: "Transform.glsl" }, - { source: Skin, includeKey: "Skin.glsl" }, - - ...shadingPBR -]; -export { PBRSource, fragmentList }; diff --git a/packages/shader/src/shaders/shadingPBR/index.ts b/packages/shader/src/shaders/shadingPBR/index.ts deleted file mode 100644 index b71d0da327..0000000000 --- a/packages/shader/src/shaders/shadingPBR/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -import AttributesPBR from "./AttributesPBR.glsl"; -import ForwardPassPBR from "./ForwardPassPBR.glsl"; -import FragmentPBR from "./FragmentPBR.glsl"; -import LightDirectPBR from "./LightDirectPBR.glsl"; -import LightIndirectFunctions from "./LightIndirectFunctions.glsl"; -import LightIndirectPBR from "./LightIndirectPBR.glsl"; -import ReflectionLobe from "./ReflectionLobe.glsl"; -import VaryingsPBR from "./VaryingsPBR.glsl"; -import VertexPBR from "./VertexPBR.glsl"; -import Refraction from "./Refraction.glsl"; -import BSDF from "./BSDF.glsl"; - -export default [ - { source: ForwardPassPBR, includeKey: "ForwardPassPBR.glsl" }, - { source: AttributesPBR, includeKey: "AttributesPBR.glsl" }, - { source: VaryingsPBR, includeKey: "VaryingsPBR.glsl" }, - { source: FragmentPBR, includeKey: "FragmentPBR.glsl" }, - { source: LightDirectPBR, includeKey: "LightDirectPBR.glsl" }, - { source: LightIndirectPBR, includeKey: "LightIndirectPBR.glsl" }, - { source: VertexPBR, includeKey: "VertexPBR.glsl" }, - { source: LightIndirectFunctions, includeKey: "LightIndirectFunctions.glsl" }, - { source: ReflectionLobe, includeKey: "ReflectionLobe.glsl" }, - { source: Refraction, includeKey: "Refraction.glsl" }, - { source: BSDF, includeKey: "BSDF.glsl" } -]; diff --git a/packages/shader/src/shaders/sky/BackgroundTexture.shader b/packages/shader/src/shaders/sky/BackgroundTexture.shader new file mode 100644 index 0000000000..df08db200c --- /dev/null +++ b/packages/shader/src/shaders/sky/BackgroundTexture.shader @@ -0,0 +1,36 @@ +Shader "Sky/BackgroundTexture" { + SubShader "Default" { + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + VertexShader = BackgroundTextureVertex; + FragmentShader = BackgroundTextureFragment; + + #include "Common/Common.glsl" + + struct Attributes { + vec3 POSITION; + vec2 TEXCOORD_0; + }; + + struct Varyings { + vec2 v_uv; + }; + + vec4 camera_ProjectionParams; + sampler2D material_BaseTexture; + + Varyings BackgroundTextureVertex(Attributes attributes) { + Varyings varyings; + gl_Position = vec4(attributes.POSITION, 1.0); + gl_Position.y *= camera_ProjectionParams.x; + varyings.v_uv = attributes.TEXCOORD_0; + return varyings; + } + + void BackgroundTextureFragment(Varyings varyings) { + gl_FragColor = texture2DSRGB(material_BaseTexture, varyings.v_uv); + } + } + } +} diff --git a/packages/shader/src/shaders/sky/SkyProcedural.shader b/packages/shader/src/shaders/sky/SkyProcedural.shader new file mode 100644 index 0000000000..197682ee18 --- /dev/null +++ b/packages/shader/src/shaders/sky/SkyProcedural.shader @@ -0,0 +1,251 @@ +// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. +// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader) + +Shader "Sky/SkyProcedural" { + SubShader "Default" { + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + VertexShader = SkyProceduralVertex; + FragmentShader = SkyProceduralFragment; + + #include "Common/Common.glsl" + + #define OUTER_RADIUS 1.025 + #define RAYLEIGH (mix(0.0, 0.0025, pow(material_AtmosphereThickness, 2.5))) + #define MIE 0.0010 + #define SUN_BRIGHTNESS 20.0 + #define MAX_SCATTER 50.0 + + const float SKY_GROUND_THRESHOLD = 0.02; + const float outerRadius = OUTER_RADIUS; + const float outerRadius2 = OUTER_RADIUS * OUTER_RADIUS; + const float innerRadius = 1.0; + const float innerRadius2 = 1.0; + const float cameraHeight = 0.0001; + + const float HDSundiskIntensityFactor = 15.0; + const float simpleSundiskIntensityFactor = 27.0; + + const float sunScale = 400.0 * SUN_BRIGHTNESS; + const float kmESun = MIE * SUN_BRIGHTNESS; + const float km4PI = MIE * 4.0 * 3.14159265; + const float scale = 1.0 / (OUTER_RADIUS - 1.0); + const float scaleDepth = 0.25; + const float scaleOverScaleDepth = (1.0 / (OUTER_RADIUS - 1.0)) / 0.25; + const float samples = 2.0; + + const vec3 c_DefaultScatteringWavelength = vec3(0.65, 0.57, 0.475); + const vec3 c_VariableRangeForScatteringWavelength = vec3(0.15, 0.15, 0.15); + + const float MIE_G = -0.990; + const float MIE_G2 = 0.9801; + + struct Attributes { + vec4 POSITION; + }; + + struct Varyings { + vec3 v_GroundColor; + vec3 v_SkyColor; + #ifdef MATERIAL_SUN_HIGH_QUALITY + vec3 v_Vertex; + #elif defined(MATERIAL_SUN_SIMPLE) + vec3 v_RayDir; + #else + float v_SkyGroundFactor; + #endif + #if defined(MATERIAL_SUN_HIGH_QUALITY) || defined(MATERIAL_SUN_SIMPLE) + vec3 v_SunColor; + #endif + }; + + mat4 camera_VPMat; + vec3 material_SkyTint; + vec3 material_GroundTint; + float material_Exposure; + float material_AtmosphereThickness; + vec4 scene_SunlightColor; + vec3 scene_SunlightDirection; + float material_SunSize; + float material_SunSizeConvergence; + + #define GAMMA 2.2 + #define COLOR_2_GAMMA(color) pow(color, vec3(1.0 / GAMMA)) + #define COLOR_2_LINEAR(color) color + + float getRayleighPhase(vec3 light, vec3 ray) { + float eyeCos = dot(light, ray); + return 0.75 + 0.75 * eyeCos * eyeCos; + } + + float scaleAngle(float inCos) { + float x = 1.0 - inCos; + return 0.25 * exp(-0.00287 + x * (0.459 + x * (3.83 + x * (-6.80 + x * 5.25)))); + } + + float getMiePhase(float eyeCos, float eyeCos2) { + float temp = 1.0 + MIE_G2 - 2.0 * MIE_G * eyeCos; + temp = pow(temp, pow(material_SunSize, 0.65) * 10.0); + temp = max(temp, 1.0e-4); + temp = 1.5 * ((1.0 - MIE_G2) / (2.0 + MIE_G2)) * (1.0 + eyeCos2) / temp; + return temp; + } + + float calcSunAttenuation(vec3 lightPos, vec3 ray) { + #ifdef MATERIAL_SUN_HIGH_QUALITY + float focusedEyeCos = pow(clamp(dot(lightPos, ray), 0.0, 1.0), material_SunSizeConvergence); + return getMiePhase(-focusedEyeCos, focusedEyeCos * focusedEyeCos); + #else //MATERIAL_SUN_SIMPLE + vec3 delta = lightPos - ray; + float dist = length(delta); + float spot = 1.0 - smoothstep(0.0, material_SunSize, dist); + return spot * spot; + #endif + } + + Varyings SkyProceduralVertex(Attributes attributes) { + Varyings varyings; + + gl_Position = camera_VPMat * vec4(attributes.POSITION.xyz, 1.0); + + vec3 skyTintInGammaSpace = COLOR_2_GAMMA(material_SkyTint); + vec3 scatteringWavelength = mix( + c_DefaultScatteringWavelength - c_VariableRangeForScatteringWavelength, + c_DefaultScatteringWavelength + c_VariableRangeForScatteringWavelength, + vec3(1.0) - skyTintInGammaSpace + ); + vec3 invWavelength = 1.0 / pow(scatteringWavelength, vec3(4.0)); + + float krESun = RAYLEIGH * SUN_BRIGHTNESS; + float kr4PI = RAYLEIGH * 4.0 * 3.14159265; + + vec3 cameraPos = vec3(0.0, innerRadius + cameraHeight, 0.0); + + vec3 eyeRay = normalize(attributes.POSITION.xyz); + + float far = 0.0; + vec3 cIn, cOut; + if (eyeRay.y >= 0.0) { + // Sky + far = sqrt(outerRadius2 + innerRadius2 * eyeRay.y * eyeRay.y - innerRadius2) - innerRadius * eyeRay.y; + + float height = innerRadius + cameraHeight; + float depth = exp(scaleOverScaleDepth * -cameraHeight); + float startAngle = dot(eyeRay, cameraPos) / height; + float startOffset = depth * scaleAngle(startAngle); + + float sampleLength = far / samples; + float scaledLength = sampleLength * scale; + vec3 sampleRay = eyeRay * sampleLength; + vec3 samplePoint = cameraPos + sampleRay * 0.5; + + vec3 frontColor = vec3(0.0); + // Unrolled loop - iteration 1 + { + float height = length(samplePoint); + float depth = exp(scaleOverScaleDepth * (innerRadius - height)); + float lightAngle = dot(-scene_SunlightDirection, samplePoint) / height; + float cameraAngle = dot(eyeRay, samplePoint) / height; + float scatter = (startOffset + depth * (scaleAngle(lightAngle) - scaleAngle(cameraAngle))); + vec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); + + frontColor += attenuate * (depth * scaledLength); + samplePoint += sampleRay; + } + // Unrolled loop - iteration 2 + { + float height = length(samplePoint); + float depth = exp(scaleOverScaleDepth * (innerRadius - height)); + float lightAngle = dot(-scene_SunlightDirection, samplePoint) / height; + float cameraAngle = dot(eyeRay, samplePoint) / height; + float scatter = (startOffset + depth * (scaleAngle(lightAngle) - scaleAngle(cameraAngle))); + vec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); + + frontColor += attenuate * (depth * scaledLength); + samplePoint += sampleRay; + } + + cIn = frontColor * (invWavelength * krESun); + cOut = frontColor * kmESun; + } else { + // Ground + far = (-cameraHeight) / (min(-0.001, eyeRay.y)); + vec3 pos = cameraPos + far * eyeRay; + + float depth = exp((-cameraHeight) * (1.0 / scaleDepth)); + float cameraAngle = dot(-eyeRay, pos); + float lightAngle = dot(-scene_SunlightDirection, pos); + float cameraScale = scaleAngle(cameraAngle); + float lightScale = scaleAngle(lightAngle); + float cameraOffset = depth * cameraScale; + float temp = lightScale + cameraScale; + + float sampleLength = far / samples; + float scaledLength = sampleLength * scale; + vec3 sampleRay = eyeRay * sampleLength; + vec3 samplePoint = cameraPos + sampleRay * 0.5; + + vec3 frontColor = vec3(0.0, 0.0, 0.0); + vec3 attenuate; + + { + float height = length(samplePoint); + float depth = exp(scaleOverScaleDepth * (innerRadius - height)); + float scatter = depth * temp - cameraOffset; + attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI)); + frontColor += attenuate * (depth * scaledLength); + samplePoint += sampleRay; + } + + cIn = frontColor * (invWavelength * krESun + kmESun); + cOut = clamp(attenuate, 0.0, 1.0); + } + + #ifdef MATERIAL_SUN_HIGH_QUALITY + varyings.v_Vertex = -attributes.POSITION.xyz; + #elif defined(MATERIAL_SUN_SIMPLE) + varyings.v_RayDir = -eyeRay; + #else + varyings.v_SkyGroundFactor = -eyeRay.y / SKY_GROUND_THRESHOLD; + #endif + + varyings.v_GroundColor = material_Exposure * (cIn + COLOR_2_LINEAR(material_GroundTint) * cOut); + varyings.v_SkyColor = material_Exposure * (cIn * getRayleighPhase(-scene_SunlightDirection, -eyeRay)); + + float lightColorIntensity = clamp(length(scene_SunlightColor.xyz), 0.25, 1.0); + + #ifdef MATERIAL_SUN_HIGH_QUALITY + varyings.v_SunColor = HDSundiskIntensityFactor * clamp(cOut, 0.0, 1.0) * scene_SunlightColor.xyz / lightColorIntensity; + #elif defined(MATERIAL_SUN_SIMPLE) + varyings.v_SunColor = simpleSundiskIntensityFactor * clamp(cOut * sunScale, 0.0, 1.0) * scene_SunlightColor.xyz / lightColorIntensity; + #endif + + return varyings; + } + + void SkyProceduralFragment(Varyings varyings) { + vec3 col = vec3(0.0, 0.0, 0.0); + + #ifdef MATERIAL_SUN_HIGH_QUALITY + vec3 ray = normalize(varyings.v_Vertex); + float y = ray.y / SKY_GROUND_THRESHOLD; + #elif defined(MATERIAL_SUN_SIMPLE) + vec3 ray = varyings.v_RayDir; + float y = ray.y / SKY_GROUND_THRESHOLD; + #else + float y = varyings.v_SkyGroundFactor; + #endif + + col = mix(varyings.v_SkyColor, varyings.v_GroundColor, clamp(y, 0.0, 1.0)); + + #if defined(MATERIAL_SUN_HIGH_QUALITY) || defined(MATERIAL_SUN_SIMPLE) + if (y < 0.0) + col += varyings.v_SunColor * calcSunAttenuation(-scene_SunlightDirection, -ray); + #endif + + gl_FragColor = vec4(col, 1.0); + } + } + } +} diff --git a/packages/shader/src/shaders/sky/Skybox.shader b/packages/shader/src/shaders/sky/Skybox.shader new file mode 100644 index 0000000000..d76f44ca78 --- /dev/null +++ b/packages/shader/src/shaders/sky/Skybox.shader @@ -0,0 +1,51 @@ +Shader "Sky/Skybox" { + SubShader "Default" { + Pass "Forward Pass" { + Tags { pipelineStage = "Forward" } + + VertexShader = SkyboxVertex; + FragmentShader = SkyboxFragment; + + #include "Common/Common.glsl" + + struct Attributes { + vec3 POSITION; + }; + + struct Varyings { + vec3 v_cubeUV; + }; + + mat4 camera_VPMat; + float material_Rotation; + samplerCube material_CubeTexture; + float material_Exposure; + vec4 material_TintColor; + + vec4 rotateY(vec4 v, float angle) { + const float deg2rad = 3.1415926 / 180.0; + float radian = angle * deg2rad; + float sina = sin(radian); + float cosa = cos(radian); + mat2 m = mat2(cosa, -sina, sina, cosa); + return vec4(m * v.xz, v.yw).xzyw; + } + + Varyings SkyboxVertex(Attributes attributes) { + Varyings varyings; + varyings.v_cubeUV = attributes.POSITION; + gl_Position = camera_VPMat * rotateY(vec4(attributes.POSITION, 1.0), material_Rotation); + return varyings; + } + + void SkyboxFragment(Varyings varyings) { + vec4 textureColor = textureCube(material_CubeTexture, varyings.v_cubeUV); + #ifdef ENGINE_NO_SRGB + textureColor = sRGBToLinear(textureColor); + #endif + textureColor.rgb *= material_Exposure * material_TintColor.rgb; + gl_FragColor = textureColor; + } + } + } +} diff --git a/packages/shader/src/shaders/utility/Blit.shader b/packages/shader/src/shaders/utility/Blit.shader new file mode 100644 index 0000000000..6e7469f4d7 --- /dev/null +++ b/packages/shader/src/shaders/utility/Blit.shader @@ -0,0 +1,54 @@ +Shader "Utility/Blit" { + SubShader "Default" { + Pass "Forward" { + Tags { pipelineStage = "Forward" } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + + mediump sampler2D renderer_BlitTexture; + #ifdef HAS_TEX_LOD + float renderer_BlitMipLevel; + #endif + vec4 renderer_SourceScaleOffset; + + struct Attributes { + vec4 POSITION_UV; + }; + + struct Varyings { + vec2 v_uv; + }; + + Varyings vert(Attributes attr) { + Varyings v; + gl_Position = vec4(attr.POSITION_UV.xy, 0.0, 1.0); + v.v_uv = attr.POSITION_UV.zw; + return v; + } + + #ifdef HAS_TEX_LOD + vec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) { + vec4 color = texture2DLodEXT(tex, uv, lod); + #ifdef ENGINE_NO_SRGB + color = sRGBToLinear(color); + #endif + return color; + } + #endif + + void frag(Varyings v) { + vec2 uv = v.v_uv; + uv = uv * renderer_SourceScaleOffset.xy + renderer_SourceScaleOffset.zw; + + #ifdef HAS_TEX_LOD + gl_FragColor = texture2DLodSRGB(renderer_BlitTexture, uv, renderer_BlitMipLevel); + #else + gl_FragColor = texture2DSRGB(renderer_BlitTexture, uv); + #endif + } + } + } +} diff --git a/packages/shader/src/shaders/utility/BlitScreen.shader b/packages/shader/src/shaders/utility/BlitScreen.shader new file mode 100644 index 0000000000..ff98b60d72 --- /dev/null +++ b/packages/shader/src/shaders/utility/BlitScreen.shader @@ -0,0 +1,57 @@ +Shader "Utility/BlitScreen" { + SubShader "Default" { + Pass "Forward" { + Tags { pipelineStage = "Forward" } + + VertexShader = vert; + FragmentShader = frag; + + #include "Common/Common.glsl" + + mediump sampler2D renderer_BlitTexture; + #ifdef HAS_TEX_LOD + float renderer_BlitMipLevel; + #endif + + struct Attributes { + vec4 POSITION_UV; + }; + + struct Varyings { + vec2 v_uv; + }; + + Varyings vert(Attributes attr) { + Varyings v; + gl_Position = vec4(attr.POSITION_UV.xy, 0.0, 1.0); + v.v_uv = attr.POSITION_UV.zw; + return v; + } + + #ifdef HAS_TEX_LOD + vec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) { + vec4 color = texture2DLodEXT(tex, uv, lod); + #ifdef ENGINE_NO_SRGB + color = sRGBToLinear(color); + #endif + return color; + } + #endif + + void frag(Varyings v) { + vec2 uv = v.v_uv; + // Screen uv is flipped + uv.y = 1.0 - uv.y; + + #ifdef HAS_TEX_LOD + gl_FragColor = texture2DLodSRGB(renderer_BlitTexture, uv, renderer_BlitMipLevel); + #else + gl_FragColor = texture2D(renderer_BlitTexture, uv); + #endif + + // Color space in screen is in gamma space but without sRGB texture, so convert to linear space + gl_FragColor = sRGBToLinear(gl_FragColor); + } + } + } +} diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index ea5b3a6b38..6d5c40ae65 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -6,14 +6,10 @@ import { Entity, Loader, Material, - PipelineStage, RenderQueueType, - Shader, - ShaderPass + Shader } from "@galacean/engine"; import * as GUIComponent from "./component"; -import uiDefaultFs from "./shader/uiDefault.fs.glsl"; -import uiDefaultVs from "./shader/uiDefault.vs.glsl"; export * from "./component"; export { CanvasRenderMode } from "./enums/CanvasRenderMode"; export { HorizontalAlignmentMode } from "./enums/HorizontalAlignmentMode"; @@ -98,13 +94,5 @@ export function registerGUI() { } function _getOrCreateUIShader(): Shader { - let shader = Shader.find("ui"); - if (!shader) { - shader = Shader.create("ui", [ - new ShaderPass("Forward", uiDefaultVs, uiDefaultFs, { - pipelineStage: PipelineStage.Forward - }) - ]); - } - return shader; + return Shader.find("2D/UIDefault"); } diff --git a/packages/ui/src/shader/global.d.ts b/packages/ui/src/shader/global.d.ts deleted file mode 100644 index 8ce5f33757..0000000000 --- a/packages/ui/src/shader/global.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare module "*.glsl" { - const value: string; - export default value; -} - -declare module "*.shader" { - const value: string; - export default value; -} diff --git a/packages/ui/src/shader/uiDefault.fs.glsl b/packages/ui/src/shader/uiDefault.fs.glsl deleted file mode 100644 index e4028405de..0000000000 --- a/packages/ui/src/shader/uiDefault.fs.glsl +++ /dev/null @@ -1,14 +0,0 @@ -#include -uniform sampler2D renderer_UITexture; - -varying vec2 v_uv; -varying vec4 v_color; - -void main() { - vec4 baseColor = texture2DSRGB(renderer_UITexture, v_uv); - vec4 finalColor = baseColor * v_color; - #ifdef ENGINE_SHOULD_SRGB_CORRECT - finalColor = outputSRGBCorrection(finalColor); - #endif - gl_FragColor = finalColor; -} \ No newline at end of file diff --git a/packages/ui/src/shader/uiDefault.vs.glsl b/packages/ui/src/shader/uiDefault.vs.glsl deleted file mode 100644 index 2a6b45be4e..0000000000 --- a/packages/ui/src/shader/uiDefault.vs.glsl +++ /dev/null @@ -1,15 +0,0 @@ -uniform mat4 renderer_MVPMat; - -attribute vec3 POSITION; -attribute vec2 TEXCOORD_0; -attribute vec4 COLOR_0; - -varying vec2 v_uv; -varying vec4 v_color; - -void main() { - gl_Position = renderer_MVPMat * vec4(POSITION, 1.0); - - v_uv = TEXCOORD_0; - v_color = COLOR_0; -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ed565e145b..74f229fe0f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -204,6 +204,9 @@ importers: '@galacean/engine-math': specifier: workspace:* version: link:../math + '@galacean/engine-shader': + specifier: workspace:* + version: link:../shader devDependencies: '@galacean/engine-design': specifier: workspace:* @@ -275,11 +278,7 @@ importers: specifier: workspace:* version: link:../design - packages/shader: - devDependencies: - '@galacean/engine': - specifier: workspace:* - version: link:../galacean + packages/shader: {} packages/shader-lab: devDependencies: diff --git a/rollup-plugin-shaderlab.js b/rollup-plugin-shaderlab.js index e8a0974366..a0bbc676ab 100644 --- a/rollup-plugin-shaderlab.js +++ b/rollup-plugin-shaderlab.js @@ -49,14 +49,8 @@ export default function shaderlab(userOptions = {}) { globalThis.document = { createElement: () => ({}) }; } const { ShaderLab } = require("@galacean/engine-shaderlab"); - // Register built-in include fragments (Common.glsl, Light.glsl, etc.) - // so that #include directives in .gs files can be resolved. - try { - const { registerIncludes } = require("@galacean/engine-shader"); - registerIncludes(); - } catch (e) { - // @galacean/engine-shader may not be available in all contexts - } + // Built-in include fragments are auto-registered by core's ShaderPool.init() + // which runs when @galacean/engine-core is loaded. shaderLabInstance = new ShaderLab(); } return shaderLabInstance; diff --git a/tests/src/shader-lab/Precompile.test.ts b/tests/src/shader-lab/Precompile.test.ts index 4570c055b0..7c5247d881 100644 --- a/tests/src/shader-lab/Precompile.test.ts +++ b/tests/src/shader-lab/Precompile.test.ts @@ -1,6 +1,6 @@ -import { Shader, ShaderLanguage, ShaderMacro, ShaderMacroCollection, ShaderPass } from "@galacean/engine-core"; +import { Shader, ShaderLanguage, ShaderMacro, ShaderMacroCollection } from "@galacean/engine-core"; +import { PBRSource } from "@galacean/engine-shader"; import { IPrecompiledShader } from "@galacean/engine-design"; -import { registerIncludes, PBRSource } from "@galacean/engine-shader"; import { ShaderLab } from "@galacean/engine-shaderlab"; import { ShaderInstructionEncoder, ShaderInstruction } from "@galacean/engine-shaderlab/src/ShaderInstructionEncoder"; import { ShaderMacroProcessor } from "@galacean/engine-core/src/shader/ShaderMacroProcessor"; @@ -11,7 +11,6 @@ import { describe, expect, it } from "vitest"; const { readFile } = server.commands; Logger.enable(); -registerIncludes(); const shaderLab = new ShaderLab(); @@ -22,12 +21,8 @@ function makeMacroMap(entries: Array<[string, string]>): Map { describe("ShaderLab Precompile", async () => { const canvas = document.createElement("canvas"); - const engine = await WebGLEngine.create({ canvas }); + const engine = await WebGLEngine.create({ canvas, shaderLab }); - // @ts-ignore - Shader._shaderLab = shaderLab; - - const basePath = new URL("", ShaderPass._shaderRootPath).href; // ───────────────────────────────────────────────────────── // 1. JSON Serialization round-trip @@ -852,7 +847,7 @@ describe("ShaderLab Precompile", async () => { // evaluateShaderInstructions twice with the same inputs produces identical output. it("evaluateShaderInstructions is deterministic (same input → same output)", async () => { const source = await readFile("./shaders/macro-pre.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const macroCombinations: Array> = [ [], @@ -875,7 +870,7 @@ describe("ShaderLab Precompile", async () => { it("evaluateShaderInstructions output survives JSON round-trip of instructions", async () => { const source = await readFile("./shaders/macro-pre.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); for (const subShader of precompiled.subShaders) { for (const pass of subShader.passes) { @@ -896,7 +891,7 @@ describe("ShaderLab Precompile", async () => { // ───────────────────────────────────────────────────────── describe("ShaderLab._precompile()", () => { it("should produce valid IPrecompiledShader from PBR source", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); expect(typeof precompiled.name).toBe("string"); expect(precompiled.name.length).toBeGreaterThan(0); @@ -905,7 +900,7 @@ describe("ShaderLab Precompile", async () => { }); it("precompiled output should match live compilation for each pass", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const liveSource = shaderLab._parseShaderSource(PBRSource); for (let i = 0; i < liveSource.subShaders.length; i++) { @@ -926,8 +921,7 @@ describe("ShaderLab Precompile", async () => { livePass.contents, livePass.vertexEntry, livePass.fragmentEntry, - ShaderLanguage.GLSLES100, - basePath + ShaderLanguage.GLSLES100 ); // Both paths produce instructions from the same CodeGen output expect(precompiledPass.vertexShaderInstructions).toEqual(liveProgram.vertexShaderInstructions); @@ -938,14 +932,14 @@ describe("ShaderLab Precompile", async () => { }); it("output should survive JSON round-trip", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const restored = JSON.parse(JSON.stringify(precompiled)) as IPrecompiledShader; expect(restored.name).toBe(precompiled.name); expect(restored.subShaders.length).toBe(precompiled.subShaders.length); }); it("output should survive JSON stringify → parse round-trip", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const restored: IPrecompiledShader = JSON.parse(JSON.stringify(precompiled)); for (let i = 0; i < precompiled.subShaders.length; i++) { @@ -960,7 +954,7 @@ describe("ShaderLab Precompile", async () => { it("simple shader (noFragArgs) → instructions should be single TEXT", async () => { const source = await readFile("./shaders/noFragArgs.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); for (const subShader of precompiled.subShaders) { for (const pass of subShader.passes) { @@ -976,7 +970,7 @@ describe("ShaderLab Precompile", async () => { it("macro-heavy shader → instructions with conditionals", async () => { const source = await readFile("./shaders/macro-pre.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); let foundMacroPass = false; for (const subShader of precompiled.subShaders) { @@ -995,7 +989,7 @@ describe("ShaderLab Precompile", async () => { it("multi-pass shader → renderStates have constantMap entries (BlendState)", async () => { const source = await readFile("./shaders/multi-pass.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); let hasConstant = false; for (const subShader of precompiled.subShaders) { @@ -1010,7 +1004,7 @@ describe("ShaderLab Precompile", async () => { it("multi-pass shader → UsePass correctly flagged", async () => { const source = await readFile("./shaders/multi-pass.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const allPasses = precompiled.subShaders.flatMap((s) => s.passes); const usePasses = allPasses.filter((p) => p.isUsePass); @@ -1026,13 +1020,13 @@ describe("ShaderLab Precompile", async () => { }); it("GLSLES300 platformTarget is preserved in output", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES300, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES300); expect(precompiled.platformTarget).toBe(ShaderLanguage.GLSLES300); }); it("subShader tags are preserved", async () => { const source = await readFile("./shaders/macro-pre.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const sub = precompiled.subShaders[0]; expect(sub.tags).toBeDefined(); @@ -1041,7 +1035,7 @@ describe("ShaderLab Precompile", async () => { it("pass tags are preserved", async () => { const source = await readFile("./shaders/noFragArgs.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const pass = precompiled.subShaders[0].passes[0]; expect(pass.tags).toBeDefined(); @@ -1054,7 +1048,7 @@ describe("ShaderLab Precompile", async () => { // ───────────────────────────────────────────────────────── describe("Shader._createFromPrecompiled()", () => { it("should create Shader with correct name and subShader count", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestPBR_CFP_1" }; const shader = Shader._createFromPrecompiled(testData); @@ -1067,7 +1061,7 @@ describe("ShaderLab Precompile", async () => { it("platformTarget is set on each ShaderPass", async () => { const source = await readFile("./shaders/noFragArgs.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestNoFrag_CFP_PlatformTarget" }; const shader = Shader._createFromPrecompiled(testData); @@ -1083,7 +1077,7 @@ describe("ShaderLab Precompile", async () => { it("_vertexShaderInstructions / _fragmentShaderInstructions are set correctly", async () => { const source = await readFile("./shaders/noFragArgs.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestNoFrag_CFP_ShaderInstructions" }; const shader = Shader._createFromPrecompiled(testData); @@ -1101,7 +1095,7 @@ describe("ShaderLab Precompile", async () => { it("_vertexShaderInstructions populated for macro-heavy shader", async () => { const source = await readFile("./shaders/macro-pre.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestMacroPre_CFP_ShaderInstructions" }; const shader = Shader._createFromPrecompiled(testData); @@ -1123,7 +1117,7 @@ describe("ShaderLab Precompile", async () => { it("SubShader tags are preserved after _createFromPrecompiled", async () => { const source = await readFile("./shaders/macro-pre.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestMacroPre_CFP_Tags" }; const shader = Shader._createFromPrecompiled(testData); @@ -1135,7 +1129,7 @@ describe("ShaderLab Precompile", async () => { it("ShaderPass tags are preserved after _createFromPrecompiled", async () => { const source = await readFile("./shaders/noFragArgs.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestNoFrag_CFP_PassTags" }; const shader = Shader._createFromPrecompiled(testData); @@ -1146,7 +1140,7 @@ describe("ShaderLab Precompile", async () => { }); it("duplicate shader name → returns existing shader (no re-registration)", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestPBR_CFP_Duplicate" }; const first = Shader._createFromPrecompiled(testData); @@ -1159,7 +1153,7 @@ describe("ShaderLab Precompile", async () => { it("UsePass in multi-pass shader is handled without throwing", async () => { const source = await readFile("./shaders/multi-pass.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const testData = { ...precompiled, name: "TestMultiPass_CFP_UsePass" }; expect(() => Shader._createFromPrecompiled(testData)).not.toThrow(); @@ -1183,7 +1177,7 @@ describe("ShaderLab Precompile", async () => { for (const shaderFile of testShaders) { it(`${shaderFile}: precompile output matches live compilation`, async () => { const source = await readFile(`./shaders/${shaderFile}`); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const liveSource = shaderLab._parseShaderSource(source); for (let i = 0; i < liveSource.subShaders.length; i++) { @@ -1196,8 +1190,7 @@ describe("ShaderLab Precompile", async () => { livePass.contents, livePass.vertexEntry, livePass.fragmentEntry, - ShaderLanguage.GLSLES100, - basePath + ShaderLanguage.GLSLES100 ); const precompiledPass = precompiled.subShaders[i].passes[j]; @@ -1211,7 +1204,7 @@ describe("ShaderLab Precompile", async () => { it("GLSLES300 precompile output matches GLSLES300 live compilation", async () => { const source = await readFile("./shaders/noFragArgs.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES300, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES300); const liveSource = shaderLab._parseShaderSource(source); for (let i = 0; i < liveSource.subShaders.length; i++) { @@ -1222,8 +1215,7 @@ describe("ShaderLab Precompile", async () => { livePass.contents, livePass.vertexEntry, livePass.fragmentEntry, - ShaderLanguage.GLSLES300, - basePath + ShaderLanguage.GLSLES300 ); expect(precompiled.subShaders[i].passes[j].vertexShaderInstructions).toEqual(liveProgram.vertexShaderInstructions); } @@ -1236,13 +1228,13 @@ describe("ShaderLab Precompile", async () => { // ───────────────────────────────────────────────────────── describe("Performance", () => { it("JSON.parse should be faster than _precompile", () => { - const warmup = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const warmup = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const jsonStr = JSON.stringify(warmup); const RUNS = 5; const compileStart = performance.now(); for (let i = 0; i < RUNS; i++) { - shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); } const compileTime = (performance.now() - compileStart) / RUNS; @@ -1261,7 +1253,7 @@ describe("ShaderLab Precompile", async () => { it("evaluateShaderInstructions is fast on macro-heavy shader", async () => { const source = await readFile("./shaders/macro-pre.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); let fragmentShaderInstructions: ShaderInstruction[] | undefined; for (const sub of precompiled.subShaders) { diff --git a/tests/src/shader-lab/PrecompileABTest.test.ts b/tests/src/shader-lab/PrecompileABTest.test.ts index 95a8e152cd..6ac49b5b68 100644 --- a/tests/src/shader-lab/PrecompileABTest.test.ts +++ b/tests/src/shader-lab/PrecompileABTest.test.ts @@ -11,7 +11,7 @@ */ import { Shader, ShaderLanguage, ShaderMacro, ShaderMacroCollection, ShaderPass } from "@galacean/engine-core"; -import { registerIncludes, PBRSource } from "@galacean/engine-shader"; +import { PBRSource } from "@galacean/engine-shader"; import { ShaderLab } from "@galacean/engine-shaderlab"; import { ShaderMacroProcessor } from "@galacean/engine-core/src/shader/ShaderMacroProcessor"; @@ -21,7 +21,6 @@ import { describe, expect, it } from "vitest"; const { readFile } = server.commands; Logger.enable(); -registerIncludes(); const shaderLab = new ShaderLab(); @@ -110,8 +109,6 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { // @ts-ignore Shader._shaderLab = shaderLab; - // @ts-ignore - const basePath = new URL("", ShaderPass._shaderRootPath).href; // ═══════════════════════════════════════════════════════════ // A/B 1: GLSL Source Identity @@ -129,7 +126,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { it(`${file}: live instructions === precompiled instructions`, async () => { const source = await readFile(`./shaders/${file}`); const parsed = shaderLab._parseShaderSource(source); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); for (let i = 0; i < parsed.subShaders.length; i++) { for (let j = 0; j < parsed.subShaders[i].passes.length; j++) { @@ -140,8 +137,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { livePass.contents, livePass.vertexEntry, livePass.fragmentEntry, - ShaderLanguage.GLSLES100, - basePath + ShaderLanguage.GLSLES100 ); const pass = precompiled.subShaders[i].passes[j]; @@ -156,7 +152,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { const label = platform === ShaderLanguage.GLSLES100 ? "GLSLES100" : "GLSLES300"; it(`PBR (${label}): live instructions === precompiled instructions`, () => { const parsed = shaderLab._parseShaderSource(PBRSource); - const precompiled = shaderLab._precompile(PBRSource, platform, basePath); + const precompiled = shaderLab._precompile(PBRSource, platform); for (let i = 0; i < parsed.subShaders.length; i++) { for (let j = 0; j < parsed.subShaders[i].passes.length; j++) { @@ -167,8 +163,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { livePass.contents, livePass.vertexEntry, livePass.fragmentEntry, - platform, - basePath + platform ); const pass = precompiled.subShaders[i].passes[j]; expect(pass.vertexShaderInstructions).toEqual(liveProgram.vertexShaderInstructions); @@ -188,7 +183,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { platform: ShaderLanguage, macros: { name: string; value?: string }[] ) { - const precompiled = shaderLab._precompile(source, platform, basePath); + const precompiled = shaderLab._precompile(source, platform); const macroCollection = buildMacroCollection(macros); for (const sub of precompiled.subShaders) { @@ -305,7 +300,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { platform: ShaderLanguage, macros: { name: string; value?: string }[] ) { - const precompiled = shaderLab._precompile(source, platform, basePath); + const precompiled = shaderLab._precompile(source, platform); const restored = JSON.parse(JSON.stringify(precompiled)); const macroCollection = buildMacroCollection(macros); @@ -375,7 +370,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { it("multi-pass: renderStates match between paths", async () => { const source = await readFile("./shaders/multi-pass.shader"); const parsed = shaderLab._parseShaderSource(source); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); for (let i = 0; i < parsed.subShaders.length; i++) { for (let j = 0; j < parsed.subShaders[i].passes.length; j++) { @@ -402,7 +397,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { it("PBR: renderStates variableMap keys match", () => { const parsed = shaderLab._parseShaderSource(PBRSource); - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); for (let i = 0; i < parsed.subShaders.length; i++) { for (let j = 0; j < parsed.subShaders[i].passes.length; j++) { @@ -428,7 +423,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { it(`${file}: metadata matches between paths`, async () => { const source = await readFile(`./shaders/${file}`); const parsed = shaderLab._parseShaderSource(source); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); expect(precompiled.name).toBe(parsed.name); @@ -463,7 +458,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { it("macro-pre: evaluateInstructions output matches live compilation per macro combo", async () => { const source = await readFile("./shaders/macro-pre.shader"); const parsed = shaderLab._parseShaderSource(source); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); const combos: Array<{ label: string; macros: { name: string; value?: string }[] }> = [ { label: "empty", macros: [] }, @@ -493,9 +488,10 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { }); it("PBR: different macro combos produce different evaluated output", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); - const pass = precompiled.subShaders[0].passes[0]; - if (!pass.fragmentShaderInstructions) return; + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); + // Find the Forward Pass (not ShadowCaster/DepthOnly which have simple shaders) + const pass = precompiled.subShaders[0].passes.find((p) => p.name === "Forward Pass"); + if (!pass?.fragmentShaderInstructions) return; const baseMap = makeMacroMap(baseMacros); const clearCoatMap = makeMacroMap([...baseMacros, ...clearCoatMacros]); @@ -517,7 +513,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { describe("A/B: instruction optimization", () => { it("noFragArgs (single TEXT instruction): still compiles with full macro set", async () => { const source = await readFile("./shaders/noFragArgs.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); for (const sub of precompiled.subShaders) { for (const pass of sub.passes) { @@ -547,7 +543,7 @@ describe("Precompile A/B Test: Live vs Precompiled", async () => { it("mrt-struct (single TEXT instruction): compiles correctly", async () => { const source = await readFile("./shaders/mrt-struct.shader"); - const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source, ShaderLanguage.GLSLES100); for (const sub of precompiled.subShaders) { for (const pass of sub.passes) { diff --git a/tests/src/shader-lab/PrecompileBenchmark.test.ts b/tests/src/shader-lab/PrecompileBenchmark.test.ts index c3f0cb7422..e1844c896c 100644 --- a/tests/src/shader-lab/PrecompileBenchmark.test.ts +++ b/tests/src/shader-lab/PrecompileBenchmark.test.ts @@ -3,9 +3,9 @@ */ import { Shader, ShaderLanguage, ShaderMacro, ShaderMacroCollection, ShaderPass } from "@galacean/engine-core"; +import { PBRSource, ShadowMapSource, DepthOnlySource } from "@galacean/engine-shader"; import { ShaderProgram } from "@galacean/engine-core/src/shader/ShaderProgram"; import type { ShaderInstruction } from "@galacean/engine-design"; -import { registerIncludes, PBRSource } from "@galacean/engine-shader"; import { ShaderLab } from "@galacean/engine-shaderlab"; import { ShaderInstructionEncoder } from "@galacean/engine-shaderlab/src/ShaderInstructionEncoder"; import { ShaderMacroProcessor } from "@galacean/engine-core/src/shader/ShaderMacroProcessor"; @@ -16,7 +16,6 @@ import { describe, expect, it } from "vitest"; const { readFile } = server.commands; Logger.enable(); -registerIncludes(); const shaderLab = new ShaderLab(); @@ -119,8 +118,10 @@ describe("Precompile Benchmark", async () => { const engine = await WebGLEngine.create({ canvas }); // @ts-ignore Shader._shaderLab = shaderLab; - // @ts-ignore - const basePath = new URL("", ShaderPass._shaderRootPath).href; + + // Create Utility shaders first — PBR uses UsePass from them + if (!Shader.find("Utility/ShadowMap")) Shader.create(ShadowMapSource); + if (!Shader.find("Utility/DepthOnly")) Shader.create(DepthOnlySource); // Load all test shaders upfront const shaderFiles = [ @@ -150,7 +151,7 @@ describe("Precompile Benchmark", async () => { bench( label, () => { - shaderLab._precompile(source!, ShaderLanguage.GLSLES100, basePath); + shaderLab._precompile(source!, ShaderLanguage.GLSLES100); }, 10, 2 @@ -167,7 +168,7 @@ describe("Precompile Benchmark", async () => { // ═══════════════════════════════════════════════════════════ describe("2. Per-stage: parseShaderInstructions", () => { it("parseShaderInstructions timing for PBR vertex/fragment", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const results: BenchResult[] = []; for (const sub of precompiled.subShaders) { @@ -217,7 +218,7 @@ describe("Precompile Benchmark", async () => { const results: Array<{ label: string; size: number; stringify: BenchResult; parse: BenchResult }> = []; for (const { label, source } of shaderFiles) { - const precompiled = shaderLab._precompile(source!, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(source!, ShaderLanguage.GLSLES100); const strResult = bench( `${label} stringify`, () => { @@ -255,7 +256,7 @@ describe("Precompile Benchmark", async () => { // ═══════════════════════════════════════════════════════════ describe("4. Shader reconstruction", () => { it("_createFromPrecompiled vs Shader.create (PBR)", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const jsonStr = JSON.stringify(precompiled); Logger.disable(); @@ -300,7 +301,7 @@ describe("Precompile Benchmark", async () => { // ═══════════════════════════════════════════════════════════ describe("5. Macro expansion: evaluateShaderInstructions", () => { it("PBR fragment with different macro combos", () => { - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); let fragShaderInstructions: ShaderInstruction[] | undefined; for (const sub of precompiled.subShaders) { @@ -368,7 +369,7 @@ describe("Precompile Benchmark", async () => { it("precompiled (GSP) vs raw GLSL path", () => { // @ts-ignore Shader._shaderLab = shaderLab; - const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100, basePath); + const precompiled = shaderLab._precompile(PBRSource, ShaderLanguage.GLSLES100); const forwardPassData = precompiled.subShaders[0].passes.find((p) => !p.isUsePass)!; // GSP ShaderPass (with instructions) @@ -387,8 +388,7 @@ describe("Precompile Benchmark", async () => { livePassSource.contents, livePassSource.vertexEntry, livePassSource.fragmentEntry, - ShaderLanguage.GLSLES100, - basePath + ShaderLanguage.GLSLES100 )!; // Use original CodeGen GLSL (with all #ifdef branches preserved) const glslShaderPass = new ShaderPass( diff --git a/tests/src/shader-lab/ShaderLab.test.ts b/tests/src/shader-lab/ShaderLab.test.ts index e998533e5e..88b7d55e0a 100644 --- a/tests/src/shader-lab/ShaderLab.test.ts +++ b/tests/src/shader-lab/ShaderLab.test.ts @@ -7,7 +7,7 @@ import { RenderStateElementKey, StencilOperation } from "@galacean/engine-core"; -import { PBRSource, registerIncludes } from "@galacean/engine-shader"; +import { PBRSource } from "@galacean/engine-shader"; import { ShaderLab as ShaderLabRelease } from "@galacean/engine-shaderlab"; import { ShaderLab as ShaderLabVerbose } from "@galacean/engine-shaderlab/verbose"; import { glslValidate } from "./ShaderValidate"; @@ -17,7 +17,6 @@ import { server } from "@vitest/browser/context"; import { describe, expect, it } from "vitest"; const { readFile } = server.commands; Logger.enable(); -registerIncludes(); const shaderLabVerbose = new ShaderLabVerbose(); const shaderLabRelease = new ShaderLabRelease(); @@ -38,12 +37,12 @@ describe("ShaderLab", async () => { const pass1 = passList[2]; // shader name - expect(shader.name).to.equal("PBRShaderName"); + expect(shader.name).to.equal("PBR"); expect(subShader.name).to.equal("Default"); expect(pass1.name).to.equal("Forward Pass"); expect(passList.length).to.eq(3); - // Pass + // Pass (ShadowCaster and DepthOnly are UsePass from Utility shaders) expect(passList[0].isUsePass).to.be.true; expect(passList[1].isUsePass).to.be.true; expect(passList[2].name).eq("Forward Pass"); diff --git a/tests/src/shader-lab/ShaderValidate.ts b/tests/src/shader-lab/ShaderValidate.ts index 0aeff8d118..b04dc15045 100644 --- a/tests/src/shader-lab/ShaderValidate.ts +++ b/tests/src/shader-lab/ShaderValidate.ts @@ -39,9 +39,7 @@ export function glslValidate( passSource.contents, passSource.vertexEntry, passSource.fragmentEntry, - platform, - // @ts-ignore - new URL("", ShaderPass._shaderRootPath).href + platform ); if (!shaderPassSource) { diff --git a/tests/src/shader-lab/shaders/macro-pre.shader b/tests/src/shader-lab/shaders/macro-pre.shader index 87e6534e8b..6d866e1d8b 100644 --- a/tests/src/shader-lab/shaders/macro-pre.shader +++ b/tests/src/shader-lab/shaders/macro-pre.shader @@ -2,7 +2,7 @@ Shader "macro-pre-test" { SubShader "subname" { Tags { LightMode = "ForwardBase" } - UsePass "pbr/Default/Forward" + UsePass "PBR/Default/Forward Pass" Pass "default" { Tags { ReplacementTag = "Opaque" } @@ -108,6 +108,6 @@ float sampleShadowMapFiltered4(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoo } - UsePass "blinn-phong/Default/Forward" + UsePass "BlinnPhong/Default/Forward Pass" } } \ No newline at end of file diff --git a/tests/src/shader-lab/shaders/multi-pass.shader b/tests/src/shader-lab/shaders/multi-pass.shader index 2c85456021..ec74fd0042 100644 --- a/tests/src/shader-lab/shaders/multi-pass.shader +++ b/tests/src/shader-lab/shaders/multi-pass.shader @@ -143,6 +143,6 @@ Shader "multi-pass-test" { VertexShader = vert; FragmentShader = frag; } - UsePass "blinn-phong/Default/Forward" + UsePass "BlinnPhong/Default/Forward Pass" } } \ No newline at end of file