@galacean/engine-core 2.0.0-alpha.30 → 2.0.0-alpha.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1087,7 +1087,6 @@ var AssetPromise = /*#__PURE__*/ function() {
1087
1087
  /** @internal */ SystemInfo._isBrowser = true;
1088
1088
  /** Whether the system support SIMD. */ SystemInfo._simdSupported = null;
1089
1089
  SystemInfo._webpSupported = null;
1090
- SystemInfo._initialize();
1091
1090
 
1092
1091
  /**
1093
1092
  * The base class of texture, contains some common functions of texture-related classes.
@@ -4773,270 +4772,33 @@ function _extends() {
4773
4772
  return PipelineStage;
4774
4773
  }({});
4775
4774
 
4776
- var camera_declare = "uniform vec3 camera_Position;\nuniform vec3 camera_Forward; "; // eslint-disable-line
4777
-
4778
- var common = "#define PI 3.14159265359\n#define RECIPROCAL_PI 0.31830988618\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#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\n#define HALF_EPS 4.8828125e-4 // 2^-11, machine epsilon: 1 + EPS = 1 (half of the ULP for 1.0f)\n\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n\nfloat pow2(float x ) {\n return x * x;\n}\n\nvec4 gammaToLinear(vec4 value){\n return vec4( pow(value.rgb, vec3(2.2)), value.a);\n}\n\nvec4 linearToGamma(vec4 value){\n\tvalue = max(value, 0.0);\n return vec4( pow(value.rgb, vec3(1.0 / 2.2)), value.a);\n}\n\n\n// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_framebuffer_sRGB.txt\n// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_texture_sRGB_decode.txt\nfloat sRGBToLinear(float value){\n float linearRGBLo = value / 12.92;\n float linearRGBHi = pow((value + 0.055) / 1.055, 2.4);\n float linearRGB = (value <= 0.04045) ? linearRGBLo : linearRGBHi;\n return linearRGB;\n}\n\nvec4 sRGBToLinear(vec4 value){\n return vec4(sRGBToLinear(value.r), sRGBToLinear(value.g), sRGBToLinear(value.b), value.a);\n}\n\nfloat linearToSRGB(float value){\n\tvalue = max(value, 0.0);\n return (value <= 0.0031308) ? (value * 12.9232102) : 1.055 * pow(value, 1.0 / 2.4) - 0.055;\n}\n\nvec4 linearToSRGB(vec4 value){\n return vec4(linearToSRGB(value.r), linearToSRGB(value.g), linearToSRGB(value.b), value.a);\n}\n\n// Compatible with devices that do not even support EXT_sRGB in WebGL1.0.\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\tvec4 color = texture2D(tex, uv);\n\t#ifdef ENGINE_NO_SRGB\n\t\tcolor = sRGBToLinear(color);\n\t#endif\n\treturn color;\n}\n\nvec4 outputSRGBCorrection(vec4 linearIn){\n #ifdef ENGINE_OUTPUT_SRGB_CORRECT\n \treturn linearToSRGB(linearIn);\n #else \n \treturn linearIn;\n #endif\n}\n\n\nuniform vec4 camera_DepthBufferParams;\nuniform vec4 camera_ProjectionParams;\n\nfloat remapDepthBufferLinear01(float depth){\n\treturn 1.0 / (camera_DepthBufferParams.x * depth + camera_DepthBufferParams.y);\n}\n\nfloat remapDepthBufferEyeDepth(float depth){\n\t#ifdef CAMERA_ORTHOGRAPHIC\n\t\treturn camera_ProjectionParams.y + (camera_ProjectionParams.z - camera_ProjectionParams.y) * depth;\n\t#else\n\t\treturn 1.0 / (camera_DepthBufferParams.z * depth + camera_DepthBufferParams.w);\n\t#endif\n}\n\n// From Next Generation Post Processing in Call of Duty: Advanced Warfare [Jimenez 2014]\n// http://advances.realtimerendering.com/s2014/index.html\n// sampleCoord must not be normalized (e.g. window coordinates)\nfloat interleavedGradientNoise(vec2 sampleCoord)\n{\n\tconst vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189);\n\treturn fract(magic.z * fract(dot(sampleCoord, magic.xy)));\n}\n\n#ifdef GRAPHICS_API_WEBGL2\n\t#define INVERSE_MAT(mat) inverse(mat)\n#else\n\tmat2 inverseMat(mat2 m) {\n\t\treturn mat2(m[1][1],-m[0][1],\n\t\t\t\t-m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n\t}\n\tmat3 inverseMat(mat3 m) {\n\t\tfloat a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n\t\tfloat a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n\t\tfloat a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n\t\tfloat b01 = a22 * a11 - a12 * a21;\n\t\tfloat b11 = -a22 * a10 + a12 * a20;\n\t\tfloat b21 = a21 * a10 - a11 * a20;\n\n\t\tfloat det = a00 * b01 + a01 * b11 + a02 * b21;\n\n\t\treturn mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n\t\t\t\t\tb11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n\t\t\t\t\tb21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n\t}\n\tmat4 inverseMat(mat4 m) {\n\t\tfloat a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n\t\t\ta10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n\t\t\ta20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n\t\t\ta30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n\t\t\tb00 = a00 * a11 - a01 * a10,\n\t\t\tb01 = a00 * a12 - a02 * a10,\n\t\t\tb02 = a00 * a13 - a03 * a10,\n\t\t\tb03 = a01 * a12 - a02 * a11,\n\t\t\tb04 = a01 * a13 - a03 * a11,\n\t\t\tb05 = a02 * a13 - a03 * a12,\n\t\t\tb06 = a20 * a31 - a21 * a30,\n\t\t\tb07 = a20 * a32 - a22 * a30,\n\t\t\tb08 = a20 * a33 - a23 * a30,\n\t\t\tb09 = a21 * a32 - a22 * a31,\n\t\t\tb10 = a21 * a33 - a23 * a31,\n\t\t\tb11 = a22 * a33 - a23 * a32,\n\n\t\t\tdet = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n\t\treturn mat4(\n\t\t\ta11 * b11 - a12 * b10 + a13 * b09,\n\t\t\ta02 * b10 - a01 * b11 - a03 * b09,\n\t\t\ta31 * b05 - a32 * b04 + a33 * b03,\n\t\t\ta22 * b04 - a21 * b05 - a23 * b03,\n\t\t\ta12 * b08 - a10 * b11 - a13 * b07,\n\t\t\ta00 * b11 - a02 * b08 + a03 * b07,\n\t\t\ta32 * b02 - a30 * b05 - a33 * b01,\n\t\t\ta20 * b05 - a22 * b02 + a23 * b01,\n\t\t\ta10 * b10 - a11 * b08 + a13 * b06,\n\t\t\ta01 * b08 - a00 * b10 - a03 * b06,\n\t\t\ta30 * b04 - a31 * b02 + a33 * b00,\n\t\t\ta21 * b02 - a20 * b04 - a23 * b00,\n\t\t\ta11 * b07 - a10 * b09 - a12 * b06,\n\t\t\ta00 * b09 - a01 * b07 + a02 * b06,\n\t\t\ta31 * b01 - a30 * b03 - a32 * b00,\n\t\t\ta20 * b03 - a21 * b01 + a22 * b00) / det;\n\t}\n\n\t#define INVERSE_MAT(mat) inverseMat(mat)\n#endif\n\n\nvec3 safeNormalize(vec3 inVec) {\n float dp3 = max(float(HALF_MIN), dot(inVec, inVec));\n return inVec * inversesqrt(dp3);\n}\n"; // eslint-disable-line
4779
-
4780
- var common_vert = "attribute vec3 POSITION;\n\n#ifdef RENDERER_HAS_UV\n attribute vec2 TEXCOORD_0;\n#endif\n\n#ifdef RENDERER_HAS_UV1\n attribute vec2 TEXCOORD_1;\n#endif\n\n#ifdef RENDERER_HAS_SKIN\n attribute vec4 JOINTS_0;\n attribute vec4 WEIGHTS_0;\n\n #ifdef RENDERER_USE_JOINT_TEXTURE\n uniform sampler2D renderer_JointSampler;\n uniform float renderer_JointCount;\n\n mat4 getJointMatrix(sampler2D smp, float index)\n {\n float base = index / renderer_JointCount;\n float hf = 0.5 / renderer_JointCount;\n float v = base + hf;\n\n vec4 m0 = texture2D(smp, vec2(0.125, v ));\n vec4 m1 = texture2D(smp, vec2(0.375, v ));\n vec4 m2 = texture2D(smp, vec2(0.625, v ));\n vec4 m3 = texture2D(smp, vec2(0.875, v ));\n\n return mat4(m0, m1, m2, m3);\n\n }\n\n #else\n uniform mat4 renderer_JointMatrix[ RENDERER_JOINTS_NUM ];\n #endif\n#endif\n\n#ifdef RENDERER_ENABLE_VERTEXCOLOR\n attribute vec4 COLOR_0;\n#endif\n\n\n#include <transform_declare>\n#include <camera_declare>\n\nuniform vec4 material_TilingOffset;\n\n\n#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n attribute vec3 NORMAL;\n #endif\n\n #ifdef RENDERER_HAS_TANGENT\n attribute vec4 TANGENT;\n #endif\n#endif"; // eslint-disable-line
4781
-
4782
- var transform_declare = "uniform mat4 renderer_LocalMat;\nuniform mat4 renderer_ModelMat;\nuniform mat4 camera_ViewMat;\nuniform mat4 camera_ProjMat;\nuniform mat4 renderer_MVMat;\nuniform mat4 renderer_MVPMat;\nuniform mat4 renderer_NormalMat;"; // eslint-disable-line
4783
-
4784
- var color_share = "#ifdef RENDERER_ENABLE_VERTEXCOLOR\n\nvarying vec4 v_color;\n\n#endif\n"; // eslint-disable-line
4785
-
4786
- var FogFragmentDeclaration = "#if SCENE_FOG_MODE != 0\n varying vec3 v_positionVS;\n\n uniform vec4 scene_FogColor;\n uniform vec4 scene_FogParams;// (-1/(end-start), end/(end-start), density/ln(2),density/sprt(ln(2)));\n\n float ComputeFogIntensity(float fogDepth){\n #if SCENE_FOG_MODE == 1\n // (end-z) / (end-start) = z * (-1/(end-start)) + (end/(end-start))\n return clamp(fogDepth * scene_FogParams.x + scene_FogParams.y, 0.0, 1.0);\n #elif SCENE_FOG_MODE == 2\n // exp(-z * density) = exp2((-z * density)/ln(2)) = exp2(-z * density/ln(2))\n return clamp(exp2(-fogDepth * scene_FogParams.z), 0.0, 1.0);\n #elif SCENE_FOG_MODE == 3\n // exp(-(z * density)^2) = exp2(-(z * density)^2/ln(2)) = exp2(-(z * density/sprt(ln(2)))^2)\n float factor = fogDepth * scene_FogParams.w;\n return clamp(exp2(-factor * factor), 0.0, 1.0);\n #endif\n }\n#endif\n"; // eslint-disable-line
4787
-
4788
- var FogVertexDeclaration = "#if SCENE_FOG_MODE != 0\n varying vec3 v_positionVS;\n#endif\n"; // eslint-disable-line
4789
-
4790
- var PositionClipSpaceDeclaration = "#ifdef SCENE_ENABLE_AMBIENT_OCCLUSION\n varying vec4 v_PositionCS;\n#endif"; // eslint-disable-line
4791
-
4792
- var normal_share = "#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n varying vec3 v_normal;\n #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) )\n varying mat3 v_TBN;\n #endif\n #endif\n#endif"; // eslint-disable-line
4793
-
4794
- var uv_share = "varying vec2 v_uv;\n\n#ifdef RENDERER_HAS_UV1\n varying vec2 v_uv1;\n#endif"; // eslint-disable-line
4795
-
4796
- var worldpos_share = "#ifdef MATERIAL_NEED_WORLD_POS\n varying vec3 v_pos;\n#endif\n"; // eslint-disable-line
4797
-
4798
- var begin_normal_vert = "#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n vec3 normal = vec3( NORMAL );\n #endif\n\n #ifdef RENDERER_HAS_TANGENT\n vec4 tangent = vec4( TANGENT );\n #endif\n#endif"; // eslint-disable-line
4799
-
4800
- var begin_position_vert = " vec4 position = vec4( POSITION , 1.0 );\n"; // eslint-disable-line
4801
-
4802
- var blendShape_input = "#ifdef RENDERER_HAS_BLENDSHAPE\n\t#ifdef RENDERER_BLENDSHAPE_USE_TEXTURE\n\t\tuniform mediump sampler2DArray renderer_BlendShapeTexture;\n\t\tuniform ivec3 renderer_BlendShapeTextureInfo;\n\t\tuniform float renderer_BlendShapeWeights[RENDERER_BLENDSHAPE_COUNT];\n\t#else\n\t\tattribute vec3 POSITION_BS0;\n\t\tattribute vec3 POSITION_BS1;\n\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\tattribute vec3 NORMAL_BS0;\n\t\t\tattribute vec3 NORMAL_BS1;\n\t\t\tattribute vec3 TANGENT_BS0;\n\t\t\tattribute vec3 TANGENT_BS1;\n\t\t\tuniform float renderer_BlendShapeWeights[2];\n\t\t#else\n\t\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) || defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\t\tattribute vec3 POSITION_BS2;\n\t\t\t\tattribute vec3 POSITION_BS3;\n\t\t\t\t#ifdef RENDERER_BLENDSHAPE_HAS_NORMAL\n\t\t\t\t\tattribute vec3 NORMAL_BS0;\n\t\t\t\t\tattribute vec3 NORMAL_BS1;\n\t\t\t\t\tattribute vec3 NORMAL_BS2;\n\t\t\t\t\tattribute vec3 NORMAL_BS3;\n\t\t\t\t#endif\n\n\t\t\t\t#ifdef RENDERER_BLENDSHAPE_HAS_TANGENT\n\t\t\t\t\tattribute vec3 TANGENT_BS0;\n\t\t\t\t\tattribute vec3 TANGENT_BS1;\n\t\t\t\t\tattribute vec3 TANGENT_BS2;\n\t\t\t\t\tattribute vec3 TANGENT_BS3;\n\t\t\t\t#endif\n\n\t\t\t\tuniform float renderer_BlendShapeWeights[4];\n\t\t\t#else\n\t\t\t\tattribute vec3 POSITION_BS2;\n\t\t\t\tattribute vec3 POSITION_BS3;\n\t\t\t\tattribute vec3 POSITION_BS4;\n\t\t\t\tattribute vec3 POSITION_BS5;\n\t\t\t\tattribute vec3 POSITION_BS6;\n\t\t\t\tattribute vec3 POSITION_BS7;\n\t\t\t\tuniform float renderer_BlendShapeWeights[8];\n\t\t\t#endif\n\t\t#endif\n\t#endif\n\n\t#ifdef RENDERER_BLENDSHAPE_USE_TEXTURE\n\t\tvec3 getBlendShapeVertexElement(int blendShapeIndex, int vertexElementIndex)\n\t\t{\t\t\t\n\t\t\tint y = vertexElementIndex / renderer_BlendShapeTextureInfo.y;\n\t\t\tint x = vertexElementIndex - y * renderer_BlendShapeTextureInfo.y;\n\t\t\tivec3 uv = ivec3(x, y , blendShapeIndex);\n\t\t\treturn texelFetch(renderer_BlendShapeTexture, uv, 0).xyz;\n\t\t}\n\t#endif\n#endif\n"; // eslint-disable-line
4803
-
4804
- var blendShape_vert = "#ifdef RENDERER_HAS_BLENDSHAPE\n\t#ifdef RENDERER_BLENDSHAPE_USE_TEXTURE\t\n\t\tint vertexOffset = gl_VertexID * renderer_BlendShapeTextureInfo.x;\n\t\tfor(int i = 0; i < RENDERER_BLENDSHAPE_COUNT; i++){\n\t\t\tint vertexElementOffset = vertexOffset;\n\t\t\tfloat weight = renderer_BlendShapeWeights[i];\n\t\t\t// Warnning: Multiplying by 0 creates weird precision issues, causing rendering anomalies in Ace2 Android13\n\t\t\tif(weight != 0.0){\n\t\t\t\tposition.xyz += getBlendShapeVertexElement(i, vertexElementOffset) * weight;\n\t\n\t\t\t\t#ifndef MATERIAL_OMIT_NORMAL\n\t\t\t\t\t#if defined( RENDERER_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_NORMAL )\n\t\t\t\t\t\tvertexElementOffset += 1;\n\t\t\t\t\t\tnormal += getBlendShapeVertexElement(i, vertexElementOffset) * weight;\n\t\t\t\t\t#endif\n\t\n\t\t\t\t\t#if defined( RENDERER_HAS_TANGENT ) && defined(RENDERER_BLENDSHAPE_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n\t\t\t\t\t\tvertexElementOffset += 1;\n\t\t\t\t\t\ttangent.xyz += getBlendShapeVertexElement(i, vertexElementOffset) * weight;\n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t}\n\t\t\t\n\t\t}\n\t#else\n\t\tposition.xyz += POSITION_BS0 * renderer_BlendShapeWeights[0];\n\t\tposition.xyz += POSITION_BS1 * renderer_BlendShapeWeights[1];\n\n\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\t#ifndef MATERIAL_OMIT_NORMAL\n\t\t\t\t#ifdef RENDERER_HAS_NORMAL\n\t\t\t\t\tnormal += NORMAL_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\tnormal += NORMAL_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t#endif\n\t\t\t\t#if defined( RENDERER_HAS_TANGENT ) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n\t\t\t\t\ttangent.xyz += TANGENT_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\ttangent.xyz += TANGENT_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t#endif\t\t\t\t\n\t\t\t#endif\n\t\t#else\n\t\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) || defined( RENDERER_BLENDSHAPE_HAS_TANGENT )\n\t\t\t\t#ifndef MATERIAL_OMIT_NORMAL\n\t\t\t\t\tposition.xyz += POSITION_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\t\tposition.xyz += POSITION_BS3 * renderer_BlendShapeWeights[3];\n\n\t\t\t\t\t#if defined( RENDERER_BLENDSHAPE_HAS_NORMAL ) && defined( RENDERER_HAS_NORMAL )\n\t\t\t\t\t\tnormal += NORMAL_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\t\tnormal += NORMAL_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t\t\tnormal += NORMAL_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\t\t\tnormal += NORMAL_BS3 * renderer_BlendShapeWeights[3];\n\t\t\t\t\t#endif\n\n\t\t\t\t\t#if defined(RENDERER_BLENDSHAPE_HAS_TANGENT) && defined( RENDERER_HAS_TANGENT ) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS0 * renderer_BlendShapeWeights[0];\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS1 * renderer_BlendShapeWeights[1];\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\t\t\ttangent.xyz += TANGENT_BS3 * renderer_BlendShapeWeights[3];\n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t#else\n\t\t\t\tposition.xyz += POSITION_BS2 * renderer_BlendShapeWeights[2];\n\t\t\t\tposition.xyz += POSITION_BS3 * renderer_BlendShapeWeights[3];\n\t\t\t\tposition.xyz += POSITION_BS4 * renderer_BlendShapeWeights[4];\n\t\t\t\tposition.xyz += POSITION_BS5 * renderer_BlendShapeWeights[5];\n\t\t\t\tposition.xyz += POSITION_BS6 * renderer_BlendShapeWeights[6];\n\t\t\t\tposition.xyz += POSITION_BS7 * renderer_BlendShapeWeights[7];\n\t\t\t#endif\n\t\t#endif\n\t#endif\n#endif\n\n\n"; // eslint-disable-line
4805
-
4806
- var color_vert = " #ifdef RENDERER_ENABLE_VERTEXCOLOR\n\n v_color = COLOR_0;\n\n #endif\n"; // eslint-disable-line
4807
-
4808
- var FogVertex = "#if SCENE_FOG_MODE != 0\n vec4 positionVS = renderer_MVMat * position;\n v_positionVS = positionVS.xyz / positionVS.w;\n#endif\n"; // eslint-disable-line
4809
-
4810
- var normal_vert = "#ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n v_normal = normalize( mat3(renderer_NormalMat) * normal );\n\n #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) )\n vec3 tangentW = normalize( mat3(renderer_NormalMat) * tangent.xyz );\n vec3 bitangentW = cross( v_normal, tangentW ) * tangent.w;\n\n v_TBN = mat3( tangentW, bitangentW, v_normal );\n #endif\n #endif\n#endif"; // eslint-disable-line
4811
-
4812
- var position_vert = " gl_Position = renderer_MVPMat * position;"; // eslint-disable-line
4813
-
4814
- var skinning_vert = "#ifdef RENDERER_HAS_SKIN\n\n #ifdef RENDERER_USE_JOINT_TEXTURE\n mat4 skinMatrix =\n WEIGHTS_0.x * getJointMatrix(renderer_JointSampler, JOINTS_0.x ) +\n WEIGHTS_0.y * getJointMatrix(renderer_JointSampler, JOINTS_0.y ) +\n WEIGHTS_0.z * getJointMatrix(renderer_JointSampler, JOINTS_0.z ) +\n WEIGHTS_0.w * getJointMatrix(renderer_JointSampler, JOINTS_0.w );\n\n #else\n mat4 skinMatrix =\n WEIGHTS_0.x * renderer_JointMatrix[ int( JOINTS_0.x ) ] +\n WEIGHTS_0.y * renderer_JointMatrix[ int( JOINTS_0.y ) ] +\n WEIGHTS_0.z * renderer_JointMatrix[ int( JOINTS_0.z ) ] +\n WEIGHTS_0.w * renderer_JointMatrix[ int( JOINTS_0.w ) ];\n #endif\n\n position = skinMatrix * position;\n\n #if defined(RENDERER_HAS_NORMAL) && !defined(MATERIAL_OMIT_NORMAL)\n mat3 skinNormalMatrix = INVERSE_MAT(mat3(skinMatrix));\n normal = normal * skinNormalMatrix;\n #if defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) )\n tangent.xyz = tangent.xyz * skinNormalMatrix;\n #endif\n\n #endif\n\n#endif\n"; // eslint-disable-line
4815
-
4816
- var uv_vert = "#ifdef RENDERER_HAS_UV\n v_uv = TEXCOORD_0;\n#else\n // may need this calculate normal\n v_uv = vec2( 0., 0. );\n#endif\n\n#ifdef RENDERER_HAS_UV1\n v_uv1 = TEXCOORD_1;\n#endif\n\n#ifdef MATERIAL_NEED_TILING_OFFSET\n v_uv = v_uv * material_TilingOffset.xy + material_TilingOffset.zw;\n#endif"; // eslint-disable-line
4817
-
4818
- var worldpos_vert = "#ifdef MATERIAL_NEED_WORLD_POS\n vec4 temp_pos = renderer_ModelMat * position;\n v_pos = temp_pos.xyz / temp_pos.w;\n#endif\n"; // eslint-disable-line
4819
-
4820
- var FogFragment = "#if SCENE_FOG_MODE != 0\n float fogIntensity = ComputeFogIntensity(length(v_positionVS));\n gl_FragColor.rgb = mix(scene_FogColor.rgb, gl_FragColor.rgb, fogIntensity);\n#endif\n"; // eslint-disable-line
4821
-
4822
- var PositionClipSpaceVertex = "#ifdef SCENE_ENABLE_AMBIENT_OCCLUSION\n v_PositionCS = gl_Position;\n#endif\n"; // eslint-disable-line
4823
-
4824
- var light_frag_define = "// Directional light\n#ifdef SCENE_DIRECT_LIGHT_COUNT\n\n struct DirectLight {\n vec3 color;\n vec3 direction;\n };\n\n uniform ivec2 scene_DirectLightCullingMask[SCENE_DIRECT_LIGHT_COUNT];\n uniform vec3 scene_DirectLightColor[SCENE_DIRECT_LIGHT_COUNT];\n uniform vec3 scene_DirectLightDirection[SCENE_DIRECT_LIGHT_COUNT];\n\n#endif\n\n\n// Point light\n#ifdef SCENE_POINT_LIGHT_COUNT\n\n struct PointLight {\n vec3 color;\n vec3 position;\n float distance;\n };\n\n uniform ivec2 scene_PointLightCullingMask[ SCENE_POINT_LIGHT_COUNT ];\n uniform vec3 scene_PointLightColor[ SCENE_POINT_LIGHT_COUNT ];\n uniform vec3 scene_PointLightPosition[ SCENE_POINT_LIGHT_COUNT ];\n uniform float scene_PointLightDistance[ SCENE_POINT_LIGHT_COUNT ];\n\n#endif\n\n\n// Spot light\n#ifdef SCENE_SPOT_LIGHT_COUNT\n\n struct SpotLight {\n vec3 color;\n vec3 position;\n vec3 direction;\n float distance;\n float angleCos;\n float penumbraCos;\n };\n\n uniform ivec2 scene_SpotLightCullingMask[ SCENE_SPOT_LIGHT_COUNT ];\n uniform vec3 scene_SpotLightColor[ SCENE_SPOT_LIGHT_COUNT ];\n uniform vec3 scene_SpotLightPosition[ SCENE_SPOT_LIGHT_COUNT ];\n uniform vec3 scene_SpotLightDirection[ SCENE_SPOT_LIGHT_COUNT ];\n uniform float scene_SpotLightDistance[ SCENE_SPOT_LIGHT_COUNT ];\n uniform float scene_SpotLightAngleCos[ SCENE_SPOT_LIGHT_COUNT ];\n uniform float scene_SpotLightPenumbraCos[ SCENE_SPOT_LIGHT_COUNT ];\n\n#endif\n\n// Ambient light\nstruct EnvMapLight {\n vec3 diffuse;\n float mipMapLevel;\n float diffuseIntensity;\n float specularIntensity;\n};\n\n\nuniform EnvMapLight scene_EnvMapLight;\nuniform ivec4 renderer_Layer;\n\n#ifdef SCENE_USE_SH\n uniform vec3 scene_EnvSH[9];\n#endif\n\n#ifdef SCENE_USE_SPECULAR_ENV\n uniform samplerCube scene_EnvSpecularSampler;\n#endif\n\n#ifndef GRAPHICS_API_WEBGL2\nbool isBitSet(float value, float mask, float bitIndex)\n{\n return mod(floor(value / pow(2.0, bitIndex)), 2.0) == 1.0 && mod(floor(mask / pow(2.0, bitIndex)), 2.0) == 1.0;\n}\n#endif\n\nbool isRendererCulledByLight(ivec2 rendererLayer, ivec2 lightCullingMask)\n{\n #ifdef GRAPHICS_API_WEBGL2\n return !((rendererLayer.x & lightCullingMask.x) != 0 || (rendererLayer.y & lightCullingMask.y) != 0);\n #else\n for (int i = 0; i < 16; i++) {\n if (isBitSet( float(rendererLayer.x), float(lightCullingMask.x), float(i)) || isBitSet( float(rendererLayer.y), float(lightCullingMask.y), float(i))) {\n return false;\n }\n }\n return true;\n #endif\n}\n"; // eslint-disable-line
4825
-
4826
- var mobile_material_frag = "uniform vec4 material_EmissiveColor;\nuniform vec4 material_BaseColor;\nuniform vec4 material_SpecularColor;\nuniform float material_Shininess;\nuniform float material_NormalIntensity;\nuniform float material_AlphaCutoff;\n\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\n#ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n uniform sampler2D material_SpecularTexture;\n#endif\n\n#ifdef MATERIAL_HAS_NORMALTEXTURE\n uniform sampler2D material_NormalTexture;\n#endif\n"; // eslint-disable-line
4827
-
4828
- var begin_mobile_frag = " vec4 ambient = vec4(0.0);\n vec4 emission = material_EmissiveColor;\n vec4 diffuse = material_BaseColor;\n vec4 specular = material_SpecularColor;\n\n \n\n #ifdef MATERIAL_HAS_EMISSIVETEXTURE\n emission *= texture2DSRGB(material_EmissiveTexture, v_uv);\n #endif\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n diffuse *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n diffuse *= v_color;\n #endif\n\n #ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n specular *= texture2DSRGB(material_SpecularTexture, v_uv);\n #endif\n\n ambient = vec4(scene_EnvMapLight.diffuse * scene_EnvMapLight.diffuseIntensity, 1.0) * diffuse;"; // eslint-disable-line
4829
-
4830
- var begin_viewdir_frag = "#ifdef CAMERA_ORTHOGRAPHIC\n vec3 V = -camera_Forward;\n#else\n #ifdef MATERIAL_NEED_WORLD_POS\n vec3 V = normalize( camera_Position - v_pos );\n #endif\n#endif"; // eslint-disable-line
4831
-
4832
- var mobile_blinnphong_frag = " #ifdef MATERIAL_HAS_NORMALTEXTURE\n mat3 tbn = getTBN(gl_FrontFacing);\n vec3 N = getNormalByNormalTexture(tbn, material_NormalTexture, material_NormalIntensity, v_uv, gl_FrontFacing);\n #else\n vec3 N = getNormal(gl_FrontFacing);\n #endif\n\n vec3 lightDiffuse = vec3( 0.0, 0.0, 0.0 );\n vec3 lightSpecular = vec3( 0.0, 0.0, 0.0 );\n float shadowAttenuation = 1.0;\n\n #ifdef SCENE_DIRECT_LIGHT_COUNT\n shadowAttenuation = 1.0;\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n shadowAttenuation *= sampleShadowMap();\n #endif\n\n DirectLight directionalLight;\n for( int i = 0; i < SCENE_DIRECT_LIGHT_COUNT; i++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_DirectLightCullingMask[i])){\n directionalLight.color = scene_DirectLightColor[i];\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n if (i == 0) { // Sun light index is always 0\n directionalLight.color *= shadowAttenuation;\n }\n #endif\n directionalLight.direction = scene_DirectLightDirection[i];\n \n float d = max(dot(N, -directionalLight.direction), 0.0);\n lightDiffuse += directionalLight.color * d;\n \n vec3 halfDir = normalize( V - directionalLight.direction );\n float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess );\n lightSpecular += directionalLight.color * s;\n }\n }\n\n #endif\n\n #ifdef SCENE_POINT_LIGHT_COUNT\n PointLight pointLight;\n for( int i = 0; i < SCENE_POINT_LIGHT_COUNT; i++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_PointLightCullingMask[i])){\n pointLight.color = scene_PointLightColor[i];\n pointLight.position = scene_PointLightPosition[i];\n pointLight.distance = scene_PointLightDistance[i];\n\n vec3 direction = v_pos - pointLight.position;\n float dist = length( direction );\n direction /= dist;\n float decay = clamp(1.0 - pow(dist / pointLight.distance, 4.0), 0.0, 1.0);\n\n float d = max( dot( N, -direction ), 0.0 ) * decay;\n lightDiffuse += pointLight.color * d;\n\n vec3 halfDir = normalize( V - direction );\n float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess ) * decay;\n lightSpecular += pointLight.color * s;\n }\n }\n\n #endif\n\n #ifdef SCENE_SPOT_LIGHT_COUNT\n SpotLight spotLight;\n for( int i = 0; i < SCENE_SPOT_LIGHT_COUNT; i++) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_SpotLightCullingMask[i])){\n spotLight.color = scene_SpotLightColor[i];\n spotLight.position = scene_SpotLightPosition[i];\n spotLight.direction = scene_SpotLightDirection[i];\n spotLight.distance = scene_SpotLightDistance[i];\n spotLight.angleCos = scene_SpotLightAngleCos[i];\n spotLight.penumbraCos = scene_SpotLightPenumbraCos[i];\n\n vec3 direction = spotLight.position - v_pos;\n float lightDistance = length( direction );\n direction /= lightDistance;\n float angleCos = dot( direction, -spotLight.direction );\n float decay = clamp(1.0 - pow(lightDistance/spotLight.distance, 4.0), 0.0, 1.0);\n float spotEffect = smoothstep( spotLight.penumbraCos, spotLight.angleCos, angleCos );\n float decayTotal = decay * spotEffect;\n float d = max( dot( N, direction ), 0.0 ) * decayTotal;\n lightDiffuse += spotLight.color * d;\n\n vec3 halfDir = normalize( V + direction );\n float s = pow( clamp( dot( N, halfDir ), 0.0, 1.0 ), material_Shininess ) * decayTotal;\n lightSpecular += spotLight.color * s;\n }\n }\n\n #endif\n\n diffuse *= vec4( lightDiffuse, 1.0 );\n specular *= vec4( lightSpecular, 1.0 );\n\n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if( diffuse.a < material_AlphaCutoff ) {\n discard;\n }\n #endif\n"; // eslint-disable-line
4833
-
4834
- var noise_common = "// Common helper functions for simplex noise.\n// Algorithm: Ken Perlin, \"Noise hardware\" (2001) — simplex lattice improvement over classic Perlin noise (1985).\n// GLSL implementation: Ian McEwan, Ashima Arts (MIT License) — https://github.com/ashima/webgl-noise\n\n// Modulo 289 without a division (only multiplications)\nvec4 mod289( vec4 x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\nvec3 mod289( vec3 x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\nvec2 mod289( vec2 x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\nfloat mod289( float x ) {\n\n return x - floor( x * ( 1.0 / 289.0 ) ) * 289.0;\n\n}\n\n// Modulo 7 without a division\nvec4 mod7( vec4 x ) {\n\n return x - floor( x * ( 1.0 / 7.0 ) ) * 7.0;\n\n}\n\nvec3 mod7( vec3 x ) {\n\n return x - floor( x * ( 1.0 / 7.0 ) ) * 7.0;\n\n}\n\n// Permutation polynomial: (34x^2 + x) mod 289\nvec4 permute( vec4 x ) {\n\n return mod289( ( 34.0 * x + 1.0 ) * x);\n\n}\n\nvec3 permute( vec3 x ) {\n\n return mod289( ( 34.0 * x + 1.0 ) * x );\n\n}\n\nfloat permute( float x ) {\n\n return mod289( ( ( x * 34.0 ) + 1.0 ) * x );\n\n}\n\nvec4 taylorInvSqrt( vec4 r ) {\n\n return 1.79284291400159 - 0.85373472095314 * r;\n\n}\n\nfloat taylorInvSqrt( float r ) {\n\n return 1.79284291400159 - 0.85373472095314 * r;\n\n}\n\nvec4 fade( vec4 t ) {\n\n return t * t * t * ( t * ( t * 6.0 - 15.0 ) + 10.0 );\n\n}\n\nvec3 fade( vec3 t ) {\n\n return t * t * t * ( t * ( t * 6.0 - 15.0 ) + 10.0 );\n\n}\n\nvec2 fade( vec2 t ) {\n\n return t * t * t * ( t * ( t * 6.0 - 15.0 ) + 10.0 );\n\n}\n\n#define K 0.142857142857 // 1/7\n#define Ko 0.428571428571 // 1/2-K/2\n#define K2 0.020408163265306 // 1/(7*7)\n#define Kd2 0.0714285714285 // K/2\n#define Kz 0.166666666667 // 1/6\n#define Kzo 0.416666666667 // 1/2-1/6*2\n#define jitter 1.0 // smaller jitter gives more regular pattern\n#define jitter1 0.8 // smaller jitter gives less errors in F1 F2\n"; // eslint-disable-line
4835
-
4836
- var noise_simplex_3D_grad = "// 3D simplex noise analytical gradient.\n// Algorithm: Ken Perlin, \"Noise hardware\" (2001) — simplex lattice improvement over classic Perlin noise (1985).\n// Curl noise: Robert Bridson et al., \"Curl-noise for procedural fluid flow\" (2007).\n// GLSL implementation: Ian McEwan, Ashima Arts (MIT License) — https://github.com/ashima/webgl-noise\n\nvec3 simplexGrad( vec3 v ) {\n\n const vec2 C = vec2( 1.0 / 6.0, 1.0 / 3.0 );\n const vec4 D = vec4( 0.0, 0.5, 1.0, 2.0 );\n\n // First corner\n vec3 i = floor( v + dot( v, C.yyy ) );\n vec3 x0 = v - i + dot( i, C.xxx ) ;\n\n // Other corners\n vec3 g = step( x0.yzx, x0.xyz );\n vec3 l = 1.0 - g;\n vec3 i1 = min( g.xyz, l.zxy );\n vec3 i2 = max( g.xyz, l.zxy );\n\n vec3 x1 = x0 - i1 + C.xxx;\n vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y\n vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y\n\n // Permutations\n i = mod289( i );\n vec4 p = permute( permute( permute(\n i.z + vec4( 0.0, i1.z, i2.z, 1.0 ) )\n + i.y + vec4( 0.0, i1.y, i2.y, 1.0 ) )\n + i.x + vec4( 0.0, i1.x, i2.x, 1.0 ) );\n\n // Gradients: 7x7 points over a square, mapped onto an octahedron.\n // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)\n float n_ = 0.142857142857; // 1.0/7.0\n vec3 ns = n_ * D.wyz - D.xzx;\n\n vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)\n\n vec4 x_ = floor(j * ns.z);\n vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)\n\n vec4 x = x_ * ns.x + ns.yyyy;\n vec4 y = y_ * ns.x + ns.yyyy;\n vec4 h = 1.0 - abs( x ) - abs( y );\n\n vec4 b0 = vec4( x.xy, y.xy );\n vec4 b1 = vec4( x.zw, y.zw );\n\n vec4 s0 = floor( b0 ) * 2.0 + 1.0;\n vec4 s1 = floor( b1 ) * 2.0 + 1.0;\n vec4 sh = - step( h, vec4( 0.0 ) );\n\n vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy ;\n vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww ;\n\n vec3 p0 = vec3( a0.xy, h.x );\n vec3 p1 = vec3( a0.zw, h.y );\n vec3 p2 = vec3( a1.xy, h.z );\n vec3 p3 = vec3( a1.zw, h.w );\n\n //Normalise gradients\n vec4 norm = taylorInvSqrt( vec4( dot( p0, p0 ), dot( p1, p1 ), dot( p2, p2 ), dot( p3, p3 ) ) );\n p0 *= norm.x;\n p1 *= norm.y;\n p2 *= norm.z;\n p3 *= norm.w;\n\n // Mix final noise value\n vec4 m = max( 0.6 - vec4( dot( x0, x0 ), dot( x1, x1 ), dot( x2, x2 ), dot( x3, x3 ) ), 0.0 );\n vec4 m2 = m * m;\n vec4 m4 = m2 * m2;\n vec4 pdotx = vec4( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 ), dot( p3, x3 ) );\n\n // Compute and return noise gradient\n vec4 temp = m2 * m * pdotx;\n vec3 grad = - 8.0 * ( temp.x * x0 + temp.y * x1 + temp.z * x2 + temp.w * x3 );\n grad += m4.x * p0 + m4.y * p1 + m4.z * p2 + m4.w * p3;\n return grad * 42.0;\n\n}\n"; // eslint-disable-line
4837
-
4838
- var pbr_frag_define = "#define MIN_PERCEPTUAL_ROUGHNESS 0.045\n#define MIN_ROUGHNESS 0.002025\n\nuniform float material_AlphaCutoff;\nuniform vec4 material_BaseColor;\nuniform float material_Metal;\nuniform float material_Roughness;\nuniform float material_IOR;\nuniform vec3 material_EmissiveColor;\nuniform float material_NormalIntensity;\nuniform float material_OcclusionIntensity;\nuniform float material_OcclusionTextureCoord;\nuniform float material_SpecularIntensity;\nuniform vec3 material_SpecularColor;\n\n#ifdef MATERIAL_ENABLE_CLEAR_COAT\n uniform float material_ClearCoat;\n uniform float material_ClearCoatRoughness;\n\n #ifdef MATERIAL_HAS_CLEAR_COAT_TEXTURE\n uniform sampler2D material_ClearCoatTexture;\n #endif\n\n #ifdef MATERIAL_HAS_CLEAR_COAT_ROUGHNESS_TEXTURE\n uniform sampler2D material_ClearCoatRoughnessTexture;\n #endif\n\n #ifdef MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE\n uniform sampler2D material_ClearCoatNormalTexture;\n #endif\n#endif\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n uniform vec3 material_AnisotropyInfo;\n #ifdef MATERIAL_HAS_ANISOTROPY_TEXTURE\n uniform sampler2D material_AnisotropyTexture;\n #endif\n#endif\n\n// Texture\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\n#ifdef MATERIAL_HAS_NORMALTEXTURE\n uniform sampler2D material_NormalTexture;\n#endif\n\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\n#ifdef MATERIAL_HAS_ROUGHNESS_METALLIC_TEXTURE\n uniform sampler2D material_RoughnessMetallicTexture;\n#endif\n\n#ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n uniform sampler2D material_SpecularIntensityTexture;\n#endif\n\n#ifdef MATERIAL_HAS_SPECULAR_COLOR_TEXTURE\n uniform sampler2D material_SpecularColorTexture;\n#endif\n\n#ifdef MATERIAL_HAS_OCCLUSION_TEXTURE\n uniform sampler2D material_OcclusionTexture;\n#endif\n\n\n#ifdef MATERIAL_ENABLE_SHEEN\n uniform float material_SheenRoughness;\n uniform vec3 material_SheenColor;\n #ifdef MATERIAL_HAS_SHEEN_TEXTURE\n uniform sampler2D material_SheenTexture;\n #endif\n\n #ifdef MATERIAL_HAS_SHEEN_ROUGHNESS_TEXTURE\n uniform sampler2D material_SheenRoughnessTexture;\n #endif\n#endif\n\n\n#ifdef MATERIAL_ENABLE_IRIDESCENCE\n uniform vec4 material_IridescenceInfo;\n #ifdef MATERIAL_HAS_IRIDESCENCE_THICKNESS_TEXTURE\n uniform sampler2D material_IridescenceThicknessTexture;\n #endif\n\n #ifdef MATERIAL_HAS_IRIDESCENCE_TEXTURE\n uniform sampler2D material_IridescenceTexture;\n #endif\n#endif\n\n#ifdef MATERIAL_ENABLE_TRANSMISSION\n uniform float material_Transmission;\n #ifdef MATERIAL_HAS_TRANSMISSION_TEXTURE\n uniform sampler2D material_TransmissionTexture;\n #endif\n\n #ifdef MATERIAL_HAS_THICKNESS\n uniform vec3 material_AttenuationColor;\n uniform float material_AttenuationDistance;\n uniform float material_Thickness;\n\n #ifdef MATERIAL_HAS_THICKNESS_TEXTURE\n uniform sampler2D material_ThicknessTexture;\n #endif\n #endif\n#endif\n\n// Runtime\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\n\nstruct Geometry {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n float dotNV;\n \n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n vec3 clearCoatNormal;\n float clearCoatDotNV;\n #endif\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n vec3 anisotropicT;\n vec3 anisotropicB;\n vec3 anisotropicN;\n float anisotropy;\n #endif\n};\n\nstruct Material {\n vec3 diffuseColor;\n float roughness;\n vec3 specularF0;\n vec3 resolvedSpecularF0;\n float specularF90;\n float specularIntensity;\n vec3 specularColor;\n float opacity;\n float diffuseAO;\n float specularAO;\n vec3 envSpecularDFG;\n vec3 energyCompensation; // Multi-scattering energy compensation factor\n float IOR;\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n float clearCoat;\n float clearCoatRoughness;\n #endif\n\n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n float iridescenceIOR;\n float iridescenceFactor;\n float iridescenceThickness;\n vec3 iridescenceSpecularColor;\n #endif\n\n #ifdef MATERIAL_ENABLE_SHEEN\n float sheenRoughness;\n vec3 sheenColor;\n float sheenScaling;\n float approxIBLSheenDG;\n #endif\n\n #ifdef MATERIAL_ENABLE_TRANSMISSION \n vec3 absorptionCoefficient;\n float transmission;\n float thickness;\n #endif\n};\n"; // eslint-disable-line
4839
-
4840
- var pbr_helper = "#include <normal_get>\n#include <brdf>\n#include <btdf>\n\n// direct + indirect\n#include <direct_irradiance_frag_define>\n#include <ibl_frag_define>\n\nuniform sampler2D camera_AOTexture;\n\nfloat evaluateAmbientOcclusion(vec2 uv)\n{\n #ifdef MATERIAL_IS_TRANSPARENT\n return 1.0;\n #else\n return texture2D(camera_AOTexture, uv).r;\n #endif\n}\n\n\nfloat computeSpecularOcclusion(float ambientOcclusion, float roughness, float dotNV ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n\nfloat getAARoughnessFactor(vec3 normal) {\n // Kaplanyan 2016, \"Stable specular highlights\"\n // Tokuyoshi 2017, \"Error Reduction and Simplification for Shading Anti-Aliasing\"\n // Tokuyoshi and Kaplanyan 2019, \"Improved Geometric Specular Antialiasing\"\n #ifdef HAS_DERIVATIVES\n vec3 dxy = max( abs(dFdx(normal)), abs(dFdy(normal)) );\n return max( max(dxy.x, dxy.y), dxy.z );\n #else\n return 0.0;\n #endif\n}\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n // Aniso Bent Normals\n // Mc Alley https://www.gdcvault.com/play/1022235/Rendering-the-World-of-Far \n vec3 getAnisotropicBentNormal(Geometry geometry, vec3 n, float roughness) {\n vec3 anisotropyDirection = geometry.anisotropy >= 0.0 ? geometry.anisotropicB : geometry.anisotropicT;\n vec3 anisotropicTangent = cross(anisotropyDirection, geometry.viewDir);\n vec3 anisotropicNormal = cross(anisotropicTangent, anisotropyDirection);\n // reduce stretching for (roughness < 0.2), refer to https://advances.realtimerendering.com/s2018/Siggraph%202018%20HDRP%20talk_with%20notes.pdf 80\n vec3 bentNormal = normalize( mix(n, anisotropicNormal, abs(geometry.anisotropy) * saturate( 5.0 * roughness)) );\n\n return bentNormal;\n }\n#endif\n\nvoid initGeometry(out Geometry geometry, bool isFrontFacing){\n geometry.position = v_pos;\n #ifdef CAMERA_ORTHOGRAPHIC\n geometry.viewDir = -camera_Forward;\n #else\n geometry.viewDir = normalize(camera_Position - v_pos);\n #endif\n #if defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY)\n mat3 tbn = getTBN(isFrontFacing);\n #endif\n\n #ifdef MATERIAL_HAS_NORMALTEXTURE\n geometry.normal = getNormalByNormalTexture(tbn, material_NormalTexture, material_NormalIntensity, v_uv, isFrontFacing);\n #else\n geometry.normal = getNormal(isFrontFacing);\n #endif\n\n geometry.dotNV = saturate( dot(geometry.normal, geometry.viewDir) );\n\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n #ifdef MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE\n geometry.clearCoatNormal = getNormalByNormalTexture(tbn, material_ClearCoatNormalTexture, material_NormalIntensity, v_uv, isFrontFacing);\n #else\n geometry.clearCoatNormal = getNormal(isFrontFacing);\n #endif\n geometry.clearCoatDotNV = saturate( dot(geometry.clearCoatNormal, geometry.viewDir) );\n #endif\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n float anisotropy = material_AnisotropyInfo.z;\n vec3 anisotropicDirection = vec3(material_AnisotropyInfo.xy, 0.0);\n #ifdef MATERIAL_HAS_ANISOTROPY_TEXTURE\n vec3 anisotropyTextureInfo = texture2D( material_AnisotropyTexture, v_uv ).rgb;\n anisotropy *= anisotropyTextureInfo.b;\n anisotropicDirection.xy *= anisotropyTextureInfo.rg * 2.0 - 1.0;\n #endif\n\n geometry.anisotropy = anisotropy;\n geometry.anisotropicT = normalize(tbn * anisotropicDirection);\n geometry.anisotropicB = normalize(cross(geometry.normal, geometry.anisotropicT));\n #endif\n}\n\nvoid initMaterial(out Material material, inout Geometry geometry){\n vec4 baseColor = material_BaseColor;\n float metal = material_Metal;\n float roughness = material_Roughness;\n float alphaCutoff = material_AlphaCutoff;\n material.IOR = material_IOR;\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n baseColor *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n baseColor *= v_color;\n #endif\n\n\n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if( baseColor.a < alphaCutoff ) {\n discard;\n }\n #endif\n\n #ifdef MATERIAL_HAS_ROUGHNESS_METALLIC_TEXTURE\n vec4 metalRoughMapColor = texture2D( material_RoughnessMetallicTexture, v_uv );\n roughness *= metalRoughMapColor.g;\n metal *= metalRoughMapColor.b;\n #endif\n\n // Specular\n material.specularIntensity = material_SpecularIntensity;\n material.specularColor = material_SpecularColor;\n #ifdef MATERIAL_HAS_SPECULAR_TEXTURE\n material.specularIntensity *= texture2D( material_SpecularIntensityTexture, v_uv ).a;\n #endif\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n material.clearCoat = material_ClearCoat;\n material.clearCoatRoughness = material_ClearCoatRoughness;\n #ifdef MATERIAL_HAS_CLEAR_COAT_TEXTURE\n material.clearCoat *= texture2D( material_ClearCoatTexture, v_uv ).r;\n #endif\n #ifdef MATERIAL_HAS_CLEAR_COAT_ROUGHNESS_TEXTURE\n material.clearCoatRoughness *= texture2D( material_ClearCoatRoughnessTexture, v_uv ).g;\n #endif\n material.clearCoat = saturate( material.clearCoat );\n material.clearCoatRoughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(material.clearCoatRoughness + getAARoughnessFactor(geometry.clearCoatNormal), 1.0));\n #endif\n\n #ifdef MATERIAL_IS_TRANSPARENT\n material.opacity = baseColor.a;\n #else\n material.opacity = 1.0;\n #endif\n\n material.roughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(roughness + getAARoughnessFactor(geometry.normal), 1.0));\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n geometry.anisotropicN = getAnisotropicBentNormal(geometry, geometry.normal, material.roughness);\n #endif\n\n vec3 dielectricBaseF0 = vec3(pow2( (material.IOR - 1.0) / (material.IOR + 1.0) ));\n vec3 dielectricF0 = min(dielectricBaseF0 * material.specularColor , vec3(1.0)) * material.specularIntensity;\n float dielectricF90 = material.specularIntensity; \n\n material.specularF0 = mix(dielectricF0, baseColor.rgb, metal);\n material.specularF90 = mix(dielectricF90, 1.0, metal);\n material.resolvedSpecularF0 = material.specularF0;\n\n // Simplify: albedoColor * mix((1.0 - max(max(dielectricF0.r,dielectricF0.g),dielectricF0.b)), 0.0, metallic);\n material.diffuseColor = baseColor.rgb * (1.0 - metal) * (1.0 - max(max(dielectricF0.r,dielectricF0.g),dielectricF0.b));\n // Environment BRDF\n vec2 dfg = envDFGApprox(material.roughness, geometry.dotNV);\n\n // AO\n float diffuseAO = 1.0;\n float specularAO = 1.0;\n\n #ifdef MATERIAL_HAS_OCCLUSION_TEXTURE\n vec2 aoUV = v_uv;\n #ifdef RENDERER_HAS_UV1\n if(material_OcclusionTextureCoord == 1.0){\n aoUV = v_uv1;\n }\n #endif\n diffuseAO = ((texture2D(material_OcclusionTexture, aoUV)).r - 1.0) * material_OcclusionIntensity + 1.0;\n #endif\n\n #ifdef SCENE_ENABLE_AMBIENT_OCCLUSION\n float ambientAO = evaluateAmbientOcclusion((v_PositionCS.xy / v_PositionCS.w) * 0.5 + 0.5);\n diffuseAO = min(diffuseAO, ambientAO);\n #endif\n\n #if (defined(MATERIAL_HAS_OCCLUSION_TEXTURE) || defined(SCENE_ENABLE_AMBIENT_OCCLUSION))&& defined(SCENE_USE_SPECULAR_ENV) \n specularAO = saturate( pow( geometry.dotNV + diffuseAO, exp2( - 16.0 * material.roughness - 1.0 ) ) - 1.0 + diffuseAO );\n #endif\n\n material.diffuseAO = diffuseAO;\n material.specularAO = specularAO;\n\n // Sheen\n #ifdef MATERIAL_ENABLE_SHEEN\n vec3 sheenColor = material_SheenColor;\n #ifdef MATERIAL_HAS_SHEEN_TEXTURE\n sheenColor *= texture2DSRGB(material_SheenTexture, v_uv).rgb;\n #endif\n material.sheenColor = sheenColor;\n\n material.sheenRoughness = material_SheenRoughness;\n #ifdef MATERIAL_HAS_SHEEN_ROUGHNESS_TEXTURE\n material.sheenRoughness *= texture2D(material_SheenRoughnessTexture, v_uv).a;\n #endif\n\n material.sheenRoughness = max(MIN_PERCEPTUAL_ROUGHNESS, min(material.sheenRoughness + getAARoughnessFactor(geometry.normal), 1.0));\n material.approxIBLSheenDG = prefilteredSheenDFG(geometry.dotNV, material.sheenRoughness);\n material.sheenScaling = 1.0 - material.approxIBLSheenDG * max(max(material.sheenColor.r, material.sheenColor.g), material.sheenColor.b);\n #endif\n\n // Iridescence\n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n material.iridescenceFactor = material_IridescenceInfo.x;\n material.iridescenceIOR = material_IridescenceInfo.y;\n\n #ifdef MATERIAL_HAS_IRIDESCENCE_THICKNESS_TEXTURE\n float iridescenceThicknessWeight = texture2D( material_IridescenceThicknessTexture, v_uv).g;\n material.iridescenceThickness = mix(material_IridescenceInfo.z, material_IridescenceInfo.w, iridescenceThicknessWeight);\n #else\n material.iridescenceThickness = material_IridescenceInfo.w;\n #endif\n\n #ifdef MATERIAL_HAS_IRIDESCENCE_TEXTURE\n material.iridescenceFactor *= texture2D( material_IridescenceTexture, v_uv).r;\n #endif\n \n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n float topIOR = 1.0;\n material.iridescenceSpecularColor = evalIridescenceSpecular(topIOR, geometry.dotNV, material.iridescenceIOR, material.specularF0, material.specularF90, material.iridescenceThickness);\n material.resolvedSpecularF0 = mix(material.resolvedSpecularF0, material.iridescenceSpecularColor, material.iridescenceFactor);\n #endif\n #endif\n\n material.envSpecularDFG = material.resolvedSpecularF0 * dfg.x + material.specularF90 * dfg.y;\n\n // Multi-scattering energy compensation\n // Ref: Kulla & Conty 2017, \"Revisiting Physically Based Shading at Imageworks\"\n // Ref: Lagarde & Golubev 2018, simplified multiplier approach\n material.energyCompensation = 1.0 + material.resolvedSpecularF0 * (1.0 / max(dfg.x + dfg.y, EPSILON) - 1.0);\n\n // Transmission\n #ifdef MATERIAL_ENABLE_TRANSMISSION \n material.transmission = material_Transmission;\n #ifdef MATERIAL_HAS_TRANSMISSION_TEXTURE\n material.transmission *= texture2D(material_TransmissionTexture, v_uv).r;\n #endif\n\n #ifdef MATERIAL_HAS_THICKNESS\n material.absorptionCoefficient = -log(material_AttenuationColor + HALF_EPS) / max(HALF_EPS, material_AttenuationDistance);\n material.thickness = max(material_Thickness, 0.0001);\n #ifdef MATERIAL_HAS_THICKNESS_TEXTURE\n material.thickness *= texture2D( material_ThicknessTexture, v_uv).g;\n #endif\n #endif \n #endif\n}\n\n"; // eslint-disable-line
4841
-
4842
- var brdf = "\n#ifdef MATERIAL_ENABLE_SHEEN\n uniform sampler2D scene_PrefilteredDFG;\n#endif\n\nfloat F_Schlick(float f0, float f90, float dotLH) {\n\treturn f0 + (f90 - f0) * (pow(1.0 - dotLH, 5.0));\n}\n\nvec3 F_Schlick(vec3 f0, float f90, float dotLH ) {\n\n\t// Original approximation by Christophe Schlick '94\n\t// float fresnel = pow( 1.0 - dotLH, 5.0 );\n\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\t// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\n\treturn (f90 - f0 ) * fresnel + f0;\n\n}\n\n// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2\n// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\nfloat G_GGX_SmithCorrelated(float alpha, float dotNL, float dotNV ) {\n\n\tfloat a2 = pow2( alpha );\n\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\n\treturn 0.5 / max( gv + gl, EPSILON );\n\n}\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n // Heitz 2014, \"Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs\"\n // Heitz http://jcgt.org/published/0003/02/03/paper.pdf\n float G_GGX_SmithCorrelated_Anisotropic(float at, float ab, float ToV, float BoV, float ToL, float BoL, float NoV, float NoL) {\n float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n return 0.5 / max(lambdaV + lambdaL, EPSILON);\n }\n#endif\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney’s reparameterization\nfloat D_GGX(float alpha, float dotNH ) {\n\n\tfloat a2 = pow2( alpha );\n\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\n\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n\n}\n\n#ifdef MATERIAL_ENABLE_SHEEN\n // http://www.aconty.com/pdf/s2017_pbs_imageworks_sheen.pdf\n float D_Charlie(float roughness, float dotNH) {\n float invAlpha = 1.0 / roughness;\n float cos2h = dotNH * dotNH;\n float sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16\n return (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n }\n\n // Neubelt and Pettineo 2013, \"Crafting a Next-gen Material Pipeline for The Order: 1886\".\n float V_Neubelt(float NoV, float NoL) {\n return saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n }\n\n vec3 sheenBRDF(vec3 incidentDirection, Geometry geometry, vec3 sheenColor, float sheenRoughness) {\n vec3 halfDir = normalize(incidentDirection + geometry.viewDir);\n float dotNL = saturate(dot(geometry.normal, incidentDirection));\n float dotNH = saturate(dot(geometry.normal, halfDir));\n float D = D_Charlie(sheenRoughness, dotNH);\n float V = V_Neubelt(geometry.dotNV, dotNL);\n vec3 F = sheenColor;\n return D * V * F;\n }\n\n float prefilteredSheenDFG(float dotNV, float sheenRoughness) {\n #ifdef HAS_TEX_LOD\n return texture2DLodEXT(scene_PrefilteredDFG, vec2(dotNV, sheenRoughness), 0.0).b;\n #else\n return texture2D(scene_PrefilteredDFG, vec2(dotNV, sheenRoughness),0.0).b;\n #endif \n }\n#endif\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n // GGX Distribution Anisotropic\n // https://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf Addenda\n float D_GGX_Anisotropic(float at, float ab, float ToH, float BoH, float NoH) {\n float a2 = at * ab;\n vec3 d = vec3(ab * ToH, at * BoH, a2 * NoH);\n float d2 = dot(d, d);\n float b2 = a2 / d2;\n return a2 * b2 * b2 * RECIPROCAL_PI;\n }\n#endif\n\nfloat DG_GGX(float alpha, float dotNV, float dotNL, float dotNH) {\n\tfloat D = D_GGX( alpha, dotNH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n return G * D;\n}\n\n#ifdef MATERIAL_ENABLE_ANISOTROPY\n float DG_GGX_anisotropic(vec3 h, vec3 l, Geometry geometry, float alpha, float dotNV, float dotNL, float dotNH) {\n vec3 t = geometry.anisotropicT;\n vec3 b = geometry.anisotropicB;\n vec3 v = geometry.viewDir;\n\n float dotTV = dot(t, v);\n float dotBV = dot(b, v);\n float dotTL = dot(t, l);\n float dotBL = dot(b, l);\n float dotTH = dot(t, h);\n float dotBH = dot(b, h);\n\n // Aniso parameter remapping\n // https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf page 24\n float at = max(alpha * (1.0 + geometry.anisotropy), MIN_ROUGHNESS);\n float ab = max(alpha * (1.0 - geometry.anisotropy), MIN_ROUGHNESS);\n\n // specular anisotropic BRDF\n float D = D_GGX_Anisotropic(at, ab, dotTH, dotBH, dotNH);\n float G = G_GGX_SmithCorrelated_Anisotropic(at, ab, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL);\n\n return G * D;\n }\n#endif\n\n#ifdef MATERIAL_ENABLE_IRIDESCENCE\n vec3 iorToFresnel0(vec3 transmittedIOR, float incidentIOR) {\n return pow((transmittedIOR - incidentIOR) / (transmittedIOR + incidentIOR),vec3(2.0));\n } \n\n float iorToFresnel0(float transmittedIOR, float incidentIOR) {\n return pow((transmittedIOR - incidentIOR) / (transmittedIOR + incidentIOR),2.0);\n } \n\n // Assume air interface for top\n // Note: We don't handle the case fresnel0 == 1\n vec3 fresnelToIOR(vec3 f0){\n vec3 sqrtF0 = sqrt(f0);\n return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n }\n\n // Fresnel equations for dielectric/dielectric interfaces.\n // Ref: https://belcour.github.io/blog/research/publication/2017/05/01/brdf-thin-film.html\n // Evaluation XYZ sensitivity curves in Fourier space\n vec3 evalSensitivity(float opd, vec3 shift){\n // Use Gaussian fits, given by 3 parameters: val, pos and var\n float phase = 2.0 * PI * opd * 1.0e-9;\n const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-var * pow2(phase));\n 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));\n xyz /= 1.0685e-7;\n // XYZ to RGB color space\n const mat3 XYZ_TO_RGB = mat3( 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252);\n vec3 rgb = XYZ_TO_RGB * xyz;\n return rgb;\n }\n\n vec3 evalIridescenceSpecular(float outsideIOR, float dotNV, float thinIOR, vec3 baseF0, float baseF90, float iridescenceThickness){ \n vec3 iridescence = vec3(1.0);\n // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0\n float iridescenceIOR = mix( outsideIOR, thinIOR, smoothstep( 0.0, 0.03, iridescenceThickness ) );\n // Evaluate the cosTheta on the base layer (Snell law)\n float sinTheta2Sq = pow( outsideIOR / iridescenceIOR, 2.0) * (1.0 - pow( dotNV, 2.0));\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n // Handle total internal reflection\n if (cosTheta2Sq < 0.0) {\n return iridescence;\n }\n float cosTheta2 = sqrt(cosTheta2Sq);\n \n // First interface\n float f0 = iorToFresnel0(iridescenceIOR, outsideIOR);\n float reflectance = F_Schlick(f0, baseF90, dotNV);\n float t121 = 1.0 - reflectance;\n float phi12 = 0.0;\n // iridescenceIOR has limited greater than 1.0\n // if (iridescenceIOR < outsideIOR) {phi12 = PI;} \n float phi21 = PI - phi12;\n \n // Second interface\n vec3 baseIOR = fresnelToIOR(clamp(baseF0, 0.0, 0.9999)); // guard against 1.0\n vec3 r1 = iorToFresnel0(baseIOR, iridescenceIOR);\n vec3 r23 = F_Schlick(r1, baseF90, cosTheta2);\n vec3 phi23 =vec3(0.0);\n if (baseIOR[0] < iridescenceIOR) {phi23[0] = PI;}\n if (baseIOR[1] < iridescenceIOR) {phi23[1] = PI;}\n if (baseIOR[2] < iridescenceIOR) {phi23[2] = PI;}\n \n // Phase shift\n float opd = 2.0 * iridescenceIOR * iridescenceThickness * cosTheta2;\n vec3 phi = vec3(phi21) + phi23;\n \n // Compound terms\n vec3 r123 = clamp(reflectance * r23, 1e-5, 0.9999);\n vec3 sr123 = sqrt(r123);\n vec3 rs = pow2(t121) * r23 / (vec3(1.0) - r123);\n // Reflectance term for m = 0 (DC term amplitude)\n vec3 c0 = reflectance + rs;\n iridescence = c0;\n // Reflectance term for m > 0 (pairs of diracs)\n vec3 cm = rs - t121;\n for (int m = 1; m <= 2; ++m) {\n cm *= sr123;\n vec3 sm = 2.0 * evalSensitivity(float(m) * opd, float(m) * phi);\n iridescence += cm * sm;\n }\n return iridescence = max(iridescence, vec3(0.0)); \n }\n#endif\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX(vec3 incidentDirection, Geometry geometry, Material material, vec3 normal, vec3 specularColor, float roughness ) {\n\n\tfloat alpha = pow2( roughness ); // UE4's roughness\n\n\tvec3 halfDir = normalize( incidentDirection + geometry.viewDir );\n\n\tfloat dotNL = saturate( dot( normal, incidentDirection ) );\n\tfloat dotNV = saturate( dot( normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentDirection, halfDir ) );\n\n vec3 F = F_Schlick( specularColor, material.specularF90, dotLH );\n #ifdef MATERIAL_ENABLE_IRIDESCENCE\n F = mix(F, material.iridescenceSpecularColor, material.iridescenceFactor);\n #endif\n\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n float GD = DG_GGX_anisotropic(halfDir, incidentDirection, geometry, alpha, dotNV, dotNL, dotNH);\n #else\n float GD = DG_GGX(alpha, dotNV, dotNL, dotNH);\n #endif\n\n return F * GD;\n}\n\nvec3 BRDF_Diffuse_Lambert(vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\n"; // eslint-disable-line
4843
-
4844
- var direct_irradiance_frag_define = "#include <ShadowFragmentDeclaration>\n\nvoid sheenLobe(Geometry geometry, Material material, vec3 incidentDirection, vec3 attenuationIrradiance, inout vec3 diffuseColor, inout vec3 specularColor){\n #ifdef MATERIAL_ENABLE_SHEEN\n diffuseColor *= material.sheenScaling;\n specularColor *= material.sheenScaling;\n\n specularColor += attenuationIrradiance * sheenBRDF(incidentDirection, geometry, material.sheenColor, material.sheenRoughness);\n #endif\n}\n\nvoid addDirectRadiance(vec3 incidentDirection, vec3 color, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n float attenuation = 1.0;\n\n #ifdef MATERIAL_ENABLE_CLEAR_COAT\n float clearCoatDotNL = saturate( dot( geometry.clearCoatNormal, incidentDirection ) );\n vec3 clearCoatIrradiance = clearCoatDotNL * color;\n\n reflectedLight.directSpecular += material.clearCoat * clearCoatIrradiance * BRDF_Specular_GGX( incidentDirection, geometry, material, geometry.clearCoatNormal, vec3( 0.04 ), material.clearCoatRoughness );\n attenuation -= material.clearCoat * F_Schlick(0.04, 1.0, geometry.clearCoatDotNV);\n #endif\n\n float dotNL = saturate( dot( geometry.normal, incidentDirection ) );\n vec3 irradiance = dotNL * color * PI;\n\n reflectedLight.directSpecular += attenuation * irradiance * BRDF_Specular_GGX( incidentDirection, geometry, material, geometry.normal, material.specularF0, material.roughness) * material.energyCompensation;\n reflectedLight.directDiffuse += attenuation * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n // Sheen Lobe\n sheenLobe(geometry, material, incidentDirection, attenuation * irradiance, reflectedLight.directDiffuse, reflectedLight.directSpecular);\n\n}\n\n#ifdef SCENE_DIRECT_LIGHT_COUNT\n\n void addDirectionalDirectLightRadiance(DirectLight directionalLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n vec3 color = directionalLight.color;\n vec3 direction = -directionalLight.direction;\n\n\t\taddDirectRadiance( direction, color, geometry, material, reflectedLight );\n\n }\n\n#endif\n\n#ifdef SCENE_POINT_LIGHT_COUNT\n\n\tvoid addPointDirectLightRadiance(PointLight pointLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tvec3 direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\n\t\tvec3 color = pointLight.color;\n\t\tcolor *= clamp(1.0 - pow(lightDistance/pointLight.distance, 4.0), 0.0, 1.0);\n\n\t\taddDirectRadiance( direction, color, geometry, material, reflectedLight );\n\n\t}\n\n#endif\n\n#ifdef SCENE_SPOT_LIGHT_COUNT\n\n\tvoid addSpotDirectLightRadiance(SpotLight spotLight, Geometry geometry, Material material, inout ReflectedLight reflectedLight) {\n\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tvec3 direction = normalize( lVector );\n\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( direction, -spotLight.direction );\n\n\t\tfloat spotEffect = smoothstep( spotLight.penumbraCos, spotLight.angleCos, angleCos );\n\t\tfloat decayEffect = clamp(1.0 - pow(lightDistance/spotLight.distance, 4.0), 0.0, 1.0);\n\n\t\tvec3 color = spotLight.color;\n\t\tcolor *= spotEffect * decayEffect;\n\n\t\taddDirectRadiance( direction, color, geometry, material, reflectedLight );\n\n\t}\n\n\n#endif\n\nvoid addTotalDirectRadiance(Geometry geometry, Material material, inout ReflectedLight reflectedLight){\n float shadowAttenuation = 1.0;\n\n #ifdef SCENE_DIRECT_LIGHT_COUNT\n shadowAttenuation = 1.0;\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n shadowAttenuation *= sampleShadowMap();\n #endif\n\n DirectLight directionalLight;\n for ( int i = 0; i < SCENE_DIRECT_LIGHT_COUNT; i ++ ) {\n // warning: use `continue` syntax may trigger flickering bug in safri 16.1.\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_DirectLightCullingMask[i])){\n directionalLight.color = scene_DirectLightColor[i];\n #ifdef SCENE_IS_CALCULATE_SHADOWS\n if (i == 0) { // Sun light index is always 0\n directionalLight.color *= shadowAttenuation;\n }\n #endif\n directionalLight.direction = scene_DirectLightDirection[i];\n addDirectionalDirectLightRadiance( directionalLight, geometry, material, reflectedLight );\n }\n }\n\n #endif\n\n #ifdef SCENE_POINT_LIGHT_COUNT\n\n PointLight pointLight;\n\n for ( int i = 0; i < SCENE_POINT_LIGHT_COUNT; i ++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_PointLightCullingMask[i])){\n pointLight.color = scene_PointLightColor[i];\n pointLight.position = scene_PointLightPosition[i];\n pointLight.distance = scene_PointLightDistance[i];\n\n addPointDirectLightRadiance( pointLight, geometry, material, reflectedLight );\n } \n }\n\n #endif\n\n #ifdef SCENE_SPOT_LIGHT_COUNT\n\n SpotLight spotLight;\n\n for ( int i = 0; i < SCENE_SPOT_LIGHT_COUNT; i ++ ) {\n if(!isRendererCulledByLight(renderer_Layer.xy, scene_SpotLightCullingMask[i])){\n spotLight.color = scene_SpotLightColor[i];\n spotLight.position = scene_SpotLightPosition[i];\n spotLight.direction = scene_SpotLightDirection[i];\n spotLight.distance = scene_SpotLightDistance[i];\n spotLight.angleCos = scene_SpotLightAngleCos[i];\n spotLight.penumbraCos = scene_SpotLightPenumbraCos[i];\n\n addSpotDirectLightRadiance( spotLight, geometry, material, reflectedLight );\n } \n }\n\n #endif\n}"; // eslint-disable-line
4845
-
4846
- var ibl_frag_define = "// ------------------------Diffuse------------------------\n\n// sh need be pre-scaled in CPU.\nvec3 getLightProbeIrradiance(vec3 sh[9], vec3 normal){\n vec3 result = sh[0] +\n\n sh[1] * (normal.y) +\n sh[2] * (normal.z) +\n sh[3] * (normal.x) +\n\n sh[4] * (normal.y * normal.x) +\n sh[5] * (normal.y * normal.z) +\n sh[6] * (3.0 * normal.z * normal.z - 1.0) +\n sh[7] * (normal.z * normal.x) +\n sh[8] * (normal.x * normal.x - normal.y * normal.y);\n \n return max(result, vec3(0.0));\n\n}\n\n// ------------------------Specular------------------------\n\n// Returns raw DFG approximation coefficients (split-sum LUT approximation)\nvec2 envDFGApprox(float roughness, float dotNV) {\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n return vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 envBRDFApprox(vec3 f0, float f90, float roughness, float dotNV ) {\n vec2 AB = envDFGApprox(roughness, dotNV);\n return f0 * AB.x + f90 * AB.y;\n}\n\n\nfloat getSpecularMIPLevel(float roughness, int maxMIPLevel ) {\n return roughness * float(maxMIPLevel);\n}\n\nvec3 getReflectedVector(Geometry geometry, vec3 n) {\n #ifdef MATERIAL_ENABLE_ANISOTROPY\n vec3 r = reflect(-geometry.viewDir, geometry.anisotropicN);\n #else\n vec3 r = reflect(-geometry.viewDir, n);\n #endif\n\n return r;\n}\n\nvec3 getLightProbeRadiance(Geometry geometry, vec3 normal, float roughness, int maxMIPLevel, float specularIntensity) {\n\n #ifndef SCENE_USE_SPECULAR_ENV\n return vec3(0);\n #else\n vec3 reflectVec = getReflectedVector(geometry, normal);\n\n float specularMIPLevel = getSpecularMIPLevel(roughness, maxMIPLevel );\n\n #ifdef HAS_TEX_LOD\n vec4 envMapColor = textureCubeLodEXT( scene_EnvSpecularSampler, reflectVec, specularMIPLevel );\n #else\n vec4 envMapColor = textureCube( scene_EnvSpecularSampler, reflectVec, specularMIPLevel );\n #endif\n\n #ifdef ENGINE_NO_SRGB\n envMapColor = sRGBToLinear(envMapColor);\n #endif\n \n return envMapColor.rgb * specularIntensity;\n\n #endif\n\n}\n\n\nvoid evaluateSheenIBL(Geometry geometry, Material material, float radianceAttenuation, inout vec3 diffuseColor, inout vec3 specularColor){\n #ifdef MATERIAL_ENABLE_SHEEN\n diffuseColor *= material.sheenScaling;\n specularColor *= material.sheenScaling;\n\n vec3 reflectance = material.specularAO * radianceAttenuation * material.approxIBLSheenDG * material.sheenColor;\n specularColor += reflectance;\n #endif\n}"; // eslint-disable-line
4847
-
4848
- var pbr_frag = "Geometry geometry;\nMaterial material;\nReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\ninitGeometry(geometry, gl_FrontFacing);\ninitMaterial(material, geometry);\n\n// Direct Light\naddTotalDirectRadiance(geometry, material, reflectedLight);\n\n// IBL diffuse\n#ifdef SCENE_USE_SH\n vec3 irradiance = getLightProbeIrradiance(scene_EnvSH, geometry.normal);\n irradiance *= scene_EnvMapLight.diffuseIntensity;\n#else\n vec3 irradiance = scene_EnvMapLight.diffuse * scene_EnvMapLight.diffuseIntensity;\n irradiance *= PI;\n#endif\n\nreflectedLight.indirectDiffuse += material.diffuseAO * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\n// IBL specular\nvec3 radiance = getLightProbeRadiance(geometry, geometry.normal, material.roughness, int(scene_EnvMapLight.mipMapLevel), scene_EnvMapLight.specularIntensity);\nfloat radianceAttenuation = 1.0;\n\n// IBL Clear Coat\n#ifdef MATERIAL_ENABLE_CLEAR_COAT\n vec3 clearCoatRadiance = getLightProbeRadiance( geometry, geometry.clearCoatNormal, material.clearCoatRoughness, int(scene_EnvMapLight.mipMapLevel), scene_EnvMapLight.specularIntensity );\n\n reflectedLight.indirectSpecular += material.specularAO * clearCoatRadiance * material.clearCoat * envBRDFApprox(vec3( 0.04 ), 1.0, material.clearCoatRoughness, geometry.clearCoatDotNV);\n radianceAttenuation -= material.clearCoat * F_Schlick(0.04, 1.0, geometry.clearCoatDotNV);\n#endif\n\nreflectedLight.indirectSpecular += material.specularAO * radianceAttenuation * radiance * envBRDFApprox(material.resolvedSpecularF0, material.specularF90, material.roughness, geometry.dotNV) * material.energyCompensation;\n\n\n// IBL Sheen\nevaluateSheenIBL(geometry, material, radianceAttenuation, reflectedLight.indirectDiffuse, reflectedLight.indirectSpecular);\n\n\n// Final color\nvec3 totalDiffuseColor = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\nvec3 totalSpecularColor = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\n#ifdef MATERIAL_ENABLE_TRANSMISSION \n vec3 refractionTransmitted = evaluateTransmission(geometry, material);\n totalDiffuseColor = mix(totalDiffuseColor, refractionTransmitted, material.transmission);\n#endif\n\nvec4 finalColor = vec4(totalDiffuseColor + totalSpecularColor, material.opacity);\n\n\n// Emissive\nvec3 emissiveRadiance = material_EmissiveColor;\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_uv).rgb;\n#endif\n\nfinalColor.rgb += emissiveRadiance;\n\n\ngl_FragColor = finalColor;\n"; // eslint-disable-line
4849
-
4850
- var btdf = "#include <refraction>\n\n#ifdef MATERIAL_ENABLE_TRANSMISSION \n uniform sampler2D camera_OpaqueTexture;\n vec3 evaluateTransmission(Geometry geometry, Material material) {\n RefractionModelResult ray;\n #if REFRACTION_MODE == 0 \n // RefractionMode.Sphere\n refractionModelSphere(-geometry.viewDir, geometry.position, geometry.normal, material.IOR, material.thickness, ray);\n #elif REFRACTION_MODE == 1\n // RefractionMode.Planar\n refractionModelPlanar(-geometry.viewDir, geometry.position, geometry.normal, material.IOR, material.thickness, ray);\n #endif\n\n vec3 refractedRayExit = ray.positionExit;\n\n // We calculate the screen space position of the refracted point\n vec4 samplingPositionNDC = camera_ProjMat * camera_ViewMat * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = (samplingPositionNDC.xy / samplingPositionNDC.w) * 0.5 + 0.5;\n\n // Sample the opaque texture to get the transmitted light\n vec3 refractionTransmitted = texture2DSRGB(camera_OpaqueTexture, refractionCoords).rgb;\n refractionTransmitted *= material.diffuseColor;\n \n // Use specularFGD as an approximation of the fresnel effect\n // https://blog.selfshadow.com/publications/s2017-shading-course/imageworks/s2017_pbs_imageworks_slides_v2.pdf\n refractionTransmitted *= (1.0 - material.envSpecularDFG);\n\n #ifdef MATERIAL_HAS_THICKNESS\n // Absorption coefficient from Disney: http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf\n vec3 transmittance = min(vec3(1.0), exp(-material.absorptionCoefficient * ray.transmissionLength));\n refractionTransmitted *= transmittance;\n #endif\n \n return refractionTransmitted;\n }\n#endif"; // eslint-disable-line
4851
-
4852
- var refraction = "#ifdef MATERIAL_ENABLE_TRANSMISSION \n\tstruct RefractionModelResult {\n\t float transmissionLength; // length of the transmission during refraction through the shape\n\t vec3 positionExit; // out ray position\n\t // vec3 directionExit; // out ray direction\n\t};\n\n\t//https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@15.0/manual/refraction-models.html\n\t void refractionModelSphere(vec3 V, vec3 positionWS, vec3 normalWS, float ior, float thickness, out RefractionModelResult ray) {\n\t // Refracted ray\n\t vec3 R1 = refract(V, normalWS, 1.0 / ior);\n\t // Center of the tangent sphere\n\t // vec3 C = positionWS - normalWS * thickness * 0.5;\n\n\t // Second refraction (tangent sphere out)\n\t float dist = dot(-normalWS, R1) * thickness;\n\t // Out hit point in the tangent sphere\n\t vec3 P1 = positionWS + R1 * dist;\n\t // Out normal\n\t // vec3 N1 = safeNormalize(C - P1);\n\t // Out refracted ray\n\t // vec3 R2 = refract(R1, N1, ior);\n\n\t ray.transmissionLength = dist;\n\t ray.positionExit = P1;\n\t // ray.directionExit = R2; \n\t}\n\n\tvoid refractionModelPlanar(vec3 V, vec3 positionWS, vec3 normalWS, float ior, float thickness, out RefractionModelResult ray) {\n\t // Refracted ray\n\t vec3 R = refract(V, normalWS, 1.0 / ior);\n\t // Optical depth within the thin plane\n\t float dist = thickness / max(dot(-normalWS, R), 1e-5f);\n\n\t ray.transmissionLength = dist;\n\t ray.positionExit = vec3(positionWS + R * dist);\n\t // ray.directionExit = V;\n\t}\n\n#endif"; // eslint-disable-line
4853
-
4854
- var PBRShaderLib = {
4855
- pbr_frag_define: pbr_frag_define,
4856
- pbr_helper: pbr_helper,
4857
- brdf: brdf,
4858
- direct_irradiance_frag_define: direct_irradiance_frag_define,
4859
- ibl_frag_define: ibl_frag_define,
4860
- pbr_frag: pbr_frag,
4861
- btdf: btdf,
4862
- refraction: refraction
4863
- };
4864
-
4865
- var ShadowCoord = "\nuniform mat4 scene_ShadowMatrices[SCENE_SHADOW_CASCADED_COUNT + 1];\nuniform vec4 scene_ShadowSplitSpheres[4];\n\nmediump int computeCascadeIndex(vec3 positionWS) {\n vec3 fromCenter0 = positionWS - scene_ShadowSplitSpheres[0].xyz;\n vec3 fromCenter1 = positionWS - scene_ShadowSplitSpheres[1].xyz;\n vec3 fromCenter2 = positionWS - scene_ShadowSplitSpheres[2].xyz;\n vec3 fromCenter3 = positionWS - scene_ShadowSplitSpheres[3].xyz;\n\n mediump vec4 comparison = vec4(\n dot(fromCenter0, fromCenter0) < scene_ShadowSplitSpheres[0].w,\n dot(fromCenter1, fromCenter1) < scene_ShadowSplitSpheres[1].w,\n dot(fromCenter2, fromCenter2) < scene_ShadowSplitSpheres[2].w,\n dot(fromCenter3, fromCenter3) < scene_ShadowSplitSpheres[3].w);\n comparison.yzw = clamp(comparison.yzw - comparison.xyz,0.0,1.0);//keep the nearest\n mediump vec4 indexCoefficient = vec4(4.0,3.0,2.0,1.0);\n mediump int index = 4 - int(dot(comparison, indexCoefficient));\n return index;\n}\n\nvec3 getShadowCoord() {\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n mediump int cascadeIndex = 0;\n #else\n mediump int cascadeIndex = computeCascadeIndex(v_pos);\n #endif\n\n #ifdef GRAPHICS_API_WEBGL2\n mat4 shadowMatrix = scene_ShadowMatrices[cascadeIndex];\n #else\n mat4 shadowMatrix;\n #if SCENE_SHADOW_CASCADED_COUNT == 4\n if (cascadeIndex == 0) {\n shadowMatrix = scene_ShadowMatrices[0];\n } else if (cascadeIndex == 1) {\n shadowMatrix = scene_ShadowMatrices[1];\n } else if (cascadeIndex == 2) {\n shadowMatrix = scene_ShadowMatrices[2];\n } else if (cascadeIndex == 3) {\n shadowMatrix = scene_ShadowMatrices[3];\n } else {\n shadowMatrix = scene_ShadowMatrices[4];\n }\n #endif\n #if SCENE_SHADOW_CASCADED_COUNT == 2\n if (cascadeIndex == 0) {\n shadowMatrix = scene_ShadowMatrices[0];\n } else if (cascadeIndex == 1) {\n shadowMatrix = scene_ShadowMatrices[1];\n } else {\n shadowMatrix = scene_ShadowMatrices[2];\n } \n #endif\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n if (cascadeIndex == 0) {\n shadowMatrix = scene_ShadowMatrices[0];\n } else {\n shadowMatrix = scene_ShadowMatrices[1];\n } \n #endif\n #endif\n\n vec4 shadowCoord = shadowMatrix * vec4(v_pos, 1.0);\n return shadowCoord.xyz;\n}\n"; // eslint-disable-line
4866
-
4867
- var ShadowFragmentDeclaration = "#if defined(SCENE_SHADOW_TYPE) && defined(RENDERER_IS_RECEIVE_SHADOWS)\n #define SCENE_IS_CALCULATE_SHADOWS\n#endif\n\n#ifdef SCENE_IS_CALCULATE_SHADOWS\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n varying vec3 v_shadowCoord;\n #else\n #include <ShadowCoord>\n #endif\n \n // intensity, null, fadeScale, fadeBias\n uniform vec4 scene_ShadowInfo;\n uniform vec4 scene_ShadowMapSize;\n\n #ifdef GRAPHICS_API_WEBGL2\n uniform mediump sampler2DShadow scene_ShadowMap;\n #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) textureLod(textureName, coord3 , 0.0)\n #define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2DShadow shadowMap\n #else\n uniform sampler2D scene_ShadowMap;\n #ifdef ENGINE_NO_DEPTH_TEXTURE\n const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0*256.0), 1.0/(256.0*256.0*256.0));\n /**\n * Unpack depth value.\n */\n float unpack(const in vec4 rgbaDepth) {\n return dot(rgbaDepth, bitShift);\n }\n #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (unpack(texture2D(textureName, coord3.xy)) < coord3.z ? 0.0 : 1.0)\n #else\n #define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (texture2D(textureName, coord3.xy).r < coord3.z ? 0.0 : 1.0)\n #endif\n #define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2D shadowMap\n #endif\n\n #if SCENE_SHADOW_TYPE == 2\n float sampleShadowMapFiltered4(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoord, vec4 shadowMapSize) {\n float attenuation;\n vec4 attenuation4;\n vec2 offset=shadowMapSize.xy/2.0;\n vec3 shadowCoord0=shadowCoord + vec3(-offset,0.0);\n vec3 shadowCoord1=shadowCoord + vec3(offset.x,-offset.y,0.0);\n vec3 shadowCoord2=shadowCoord + vec3(-offset.x,offset.y,0.0);\n vec3 shadowCoord3=shadowCoord + vec3(offset,0.0);\n attenuation4.x = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord0);\n attenuation4.y = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord1);\n attenuation4.z = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord2);\n attenuation4.w = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord3);\n attenuation = dot(attenuation4, vec4(0.25));\n return attenuation;\n }\n #endif\n\n #if SCENE_SHADOW_TYPE == 3\n #include <shadow_sample_tent>\n\n float sampleShadowMapFiltered9(TEXTURE2D_SHADOW_PARAM(shadowMap), vec3 shadowCoord, vec4 shadowmapSize) {\n float attenuation;\n float fetchesWeights[9];\n vec2 fetchesUV[9];\n sampleShadowComputeSamplesTent5x5(shadowmapSize, shadowCoord.xy, fetchesWeights, fetchesUV);\n attenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[0].xy, shadowCoord.z));\n attenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[1].xy, shadowCoord.z));\n attenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[2].xy, shadowCoord.z));\n attenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[3].xy, shadowCoord.z));\n attenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[4].xy, shadowCoord.z));\n attenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[5].xy, shadowCoord.z));\n attenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[6].xy, shadowCoord.z));\n attenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[7].xy, shadowCoord.z));\n attenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[8].xy, shadowCoord.z));\n return attenuation;\n }\n #endif\n\n\n float getShadowFade(vec3 positionWS){\n vec3 camToPixel = positionWS - camera_Position;\n float distanceCamToPixel2 = dot(camToPixel, camToPixel);\n return saturate( distanceCamToPixel2 * scene_ShadowInfo.z + scene_ShadowInfo.w );\n }\n\n float sampleShadowMap() {\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n vec3 shadowCoord = v_shadowCoord;\n #else\n vec3 shadowCoord = getShadowCoord();\n #endif\n \n float attenuation = 1.0;\n if(shadowCoord.z > 0.0 && shadowCoord.z < 1.0) {\n #if SCENE_SHADOW_TYPE == 1\n attenuation = SAMPLE_TEXTURE2D_SHADOW(scene_ShadowMap, shadowCoord);\n #endif\n\n #if SCENE_SHADOW_TYPE == 2\n attenuation = sampleShadowMapFiltered4(scene_ShadowMap, shadowCoord, scene_ShadowMapSize);\n #endif\n\n #if SCENE_SHADOW_TYPE == 3\n attenuation = sampleShadowMapFiltered9(scene_ShadowMap, shadowCoord, scene_ShadowMapSize);\n #endif\n\n float shadowFade = getShadowFade(v_pos);\n attenuation = mix(1.0, mix(attenuation, 1.0, shadowFade), scene_ShadowInfo.x);\n }\n return attenuation;\n }\n#endif"; // eslint-disable-line
4868
-
4869
- var shadow_sample_tent = "// ------------------------------------------------------------------\n// PCF Filtering Tent Functions\n// ------------------------------------------------------------------\n\n// Assuming a isoceles right angled triangle of height \"triangleHeight\" (as drawn below).\n// This function return the area of the triangle above the first texel(in Y the first texel).\n//\n// |\\ <-- 45 degree slop isosceles right angled triangle\n// | \\\n// ---- <-- length of this side is \"triangleHeight\"\n// _ _ _ _ <-- texels\nfloat sampleShadowGetIRTriangleTexelArea(float triangleHeight) {\n return triangleHeight - 0.5;\n}\n\n// Assuming a isoceles triangle of 1.5 texels height and 3 texels wide lying on 4 texels.\n// This function return the area of the triangle above each of those texels.\n// | <-- offset from -0.5 to 0.5, 0 meaning triangle is exactly in the center\n// / \\ <-- 45 degree slop isosceles triangle (ie tent projected in 2D)\n// / \\\n// _ _ _ _ <-- texels\n// X Y Z W <-- result indices (in computedArea.xyzw and computedAreaUncut.xyzw)\n// 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.\nvoid sampleShadowGetTexelAreasTent3x3(float offset, out vec4 computedArea, out vec4 computedAreaUncut) {\n // Compute the exterior areas,a and h is same.\n float a = offset + 0.5;\n float offsetSquaredHalved = a * a * 0.5;\n computedAreaUncut.x = computedArea.x = offsetSquaredHalved - offset;\n computedAreaUncut.w = computedArea.w = offsetSquaredHalved;\n\n // Compute the middle areas\n // For Y : We find the area in Y of as if the left section of the isoceles triangle would\n // intersect the axis between Y and Z (ie where offset = 0).\n computedAreaUncut.y = sampleShadowGetIRTriangleTexelArea(1.5 - offset);\n // This area is superior to the one we are looking for if (offset < 0) thus we need to\n // subtract the area of the triangle defined by (0,1.5-offset), (0,1.5+offset), (-offset,1.5).\n float clampedOffsetLeft = min(offset,0.0);\n float areaOfSmallLeftTriangle = clampedOffsetLeft * clampedOffsetLeft;\n computedArea.y = computedAreaUncut.y - areaOfSmallLeftTriangle;\n\n // We do the same for the Z but with the right part of the isoceles triangle\n computedAreaUncut.z = sampleShadowGetIRTriangleTexelArea(1.5 + offset);\n float clampedOffsetRight = max(offset,0.0);\n float areaOfSmallRightTriangle = clampedOffsetRight * clampedOffsetRight;\n computedArea.z = computedAreaUncut.z - areaOfSmallRightTriangle;\n}\n\n// Assuming a isoceles triangle of 2.5 texel height and 5 texels wide lying on 6 texels.\n// This function return the weight of each texels area relative to the full triangle area.\n// / \\\n// _ _ _ _ _ _ <-- texels\n// 0 1 2 3 4 5 <-- computed area indices (in texelsWeights[])\n// 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.\nvoid sampleShadowGetTexelWeightsTent5x5(float offset, out vec3 texelsWeightsA, out vec3 texelsWeightsB) {\n vec4 areaFrom3texelTriangle;\n vec4 areaUncutFrom3texelTriangle;\n sampleShadowGetTexelAreasTent3x3(offset, areaFrom3texelTriangle, areaUncutFrom3texelTriangle);\n\n // Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.\n // the 5 texel wide triangle can be seen as the 3 texel wide one but shifted up by one unit/texel.\n // 0.16 is 1/(the triangle area)\n texelsWeightsA.x = 0.16 * (areaFrom3texelTriangle.x);\n texelsWeightsA.y = 0.16 * (areaUncutFrom3texelTriangle.y);\n texelsWeightsA.z = 0.16 * (areaFrom3texelTriangle.y + 1.0);\n texelsWeightsB.x = 0.16 * (areaFrom3texelTriangle.z + 1.0);\n texelsWeightsB.y = 0.16 * (areaUncutFrom3texelTriangle.z);\n texelsWeightsB.z = 0.16 * (areaFrom3texelTriangle.w);\n}\n\n// 5x5 Tent filter (45 degree sloped triangles in U and V)\nvoid sampleShadowComputeSamplesTent5x5(vec4 shadowMapTextureTexelSize, vec2 coord, out float fetchesWeights[9], out vec2 fetchesUV[9])\n{\n // tent base is 5x5 base thus covering from 25 to 36 texels, thus we need 9 bilinear PCF fetches\n vec2 tentCenterInTexelSpace = coord.xy * shadowMapTextureTexelSize.zw;\n vec2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);\n vec2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;\n\n // find the weight of each texel based on the area of a 45 degree slop tent above each of them.\n vec3 texelsWeightsUA, texelsWeightsUB;\n vec3 texelsWeightsVA, texelsWeightsVB;\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsUA, texelsWeightsUB);\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsVA, texelsWeightsVB);\n\n // each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels\n vec3 fetchesWeightsU = vec3(texelsWeightsUA.xz, texelsWeightsUB.y) + vec3(texelsWeightsUA.y, texelsWeightsUB.xz);\n vec3 fetchesWeightsV = vec3(texelsWeightsVA.xz, texelsWeightsVB.y) + vec3(texelsWeightsVA.y, texelsWeightsVB.xz);\n\n // move the PCF bilinear fetches to respect texels weights\n vec3 fetchesOffsetsU = vec3(texelsWeightsUA.y, texelsWeightsUB.xz) / fetchesWeightsU.xyz + vec3(-2.5,-0.5,1.5);\n vec3 fetchesOffsetsV = vec3(texelsWeightsVA.y, texelsWeightsVB.xz) / fetchesWeightsV.xyz + vec3(-2.5,-0.5,1.5);\n fetchesOffsetsU *= shadowMapTextureTexelSize.xxx;\n fetchesOffsetsV *= shadowMapTextureTexelSize.yyy;\n\n vec2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTextureTexelSize.xy;\n fetchesUV[0] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.x);\n fetchesUV[1] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.x);\n fetchesUV[2] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.x);\n fetchesUV[3] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.y);\n fetchesUV[4] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.y);\n fetchesUV[5] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.y);\n fetchesUV[6] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.z);\n fetchesUV[7] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.z);\n fetchesUV[8] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.z);\n\n fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;\n fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;\n fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;\n fetchesWeights[3] = fetchesWeightsU.x * fetchesWeightsV.y;\n fetchesWeights[4] = fetchesWeightsU.y * fetchesWeightsV.y;\n fetchesWeights[5] = fetchesWeightsU.z * fetchesWeightsV.y;\n fetchesWeights[6] = fetchesWeightsU.x * fetchesWeightsV.z;\n fetchesWeights[7] = fetchesWeightsU.y * fetchesWeightsV.z;\n fetchesWeights[8] = fetchesWeightsU.z * fetchesWeightsV.z;\n}"; // eslint-disable-line
4870
-
4871
- var ShadowVertexDeclaration = "#if defined(SCENE_SHADOW_TYPE) && defined(RENDERER_IS_RECEIVE_SHADOWS)\n #define SCENE_IS_CALCULATE_SHADOWS\n#endif\n\n#ifdef SCENE_IS_CALCULATE_SHADOWS\n #if SCENE_SHADOW_CASCADED_COUNT==1\n #include <ShadowCoord>\n varying vec3 v_shadowCoord;\n #endif\n#endif"; // eslint-disable-line
4872
-
4873
- var ShadowVertex = "#ifdef SCENE_IS_CALCULATE_SHADOWS\n #if SCENE_SHADOW_CASCADED_COUNT == 1\n v_shadowCoord = getShadowCoord();\n #endif\n#endif"; // eslint-disable-line
4874
-
4875
- var ShadowLib = {
4876
- ShadowCoord: ShadowCoord,
4877
- ShadowFragmentDeclaration: ShadowFragmentDeclaration,
4878
- shadow_sample_tent: shadow_sample_tent,
4879
- ShadowVertexDeclaration: ShadowVertexDeclaration,
4880
- ShadowVertex: ShadowVertex
4881
- };
4882
-
4883
- var particle_common = "vec3 rotationByQuaternions(in vec3 v, in vec4 q) {\n return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);\n}\n\nvec4 quaternionConjugate(in vec4 q) {\n return vec4(-q.xyz, q.w);\n}\n\nvec3 rotationByEuler(in vec3 vector, in vec3 rot) {\n float halfRoll = rot.z * 0.5;\n float halfPitch = rot.x * 0.5;\n float halfYaw = rot.y * 0.5;\n\n float sinRoll = sin(halfRoll);\n float cosRoll = cos(halfRoll);\n float sinPitch = sin(halfPitch);\n float cosPitch = cos(halfPitch);\n float sinYaw = sin(halfYaw);\n float cosYaw = cos(halfYaw);\n\n float cosYawPitch = cosYaw * cosPitch;\n float sinYawPitch = sinYaw * sinPitch;\n\n float quaX = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\n float quaY = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\n float quaZ = (cosYawPitch * sinRoll) - (sinYawPitch * cosRoll);\n float quaW = (cosYawPitch * cosRoll) + (sinYawPitch * sinRoll);\n\n return rotationByQuaternions(vector, vec4(quaX, quaY, quaZ, quaW));\n}\n\n// Assume axis is normalized\nvec3 rotationByAxis(in vec3 vector, in vec3 axis, in float angle) {\n float halfAngle = angle * 0.5;\n float s = sin(halfAngle);\n\n return rotationByQuaternions(vector, vec4(axis * s, cos(halfAngle)));\n}\n\n\nfloat evaluateParticleCurve(in vec2 keys[4], in float normalizedAge) {\n float value;\n for (int i = 1; i < 4; i++) {\n vec2 key = keys[i];\n float time = key.x;\n if (time >= normalizedAge) {\n vec2 lastKey = keys[i - 1];\n float lastTime = lastKey.x;\n float age = (normalizedAge - lastTime) / (time - lastTime);\n value = mix(lastKey.y, key.y, age);\n break;\n }\n }\n return value;\n}\n\nfloat evaluateParticleCurveCumulative(in vec2 keys[4], in float normalizedAge, out float currentValue){\n float cumulativeValue = 0.0;\n for (int i = 1; i < 4; i++){\n\t vec2 key = keys[i];\n\t float time = key.x;\n\t vec2 lastKey = keys[i - 1];\n\t float lastValue = lastKey.y;\n\n\t if (time >= normalizedAge){\n\t\t float lastTime = lastKey.x;\n float offsetTime = normalizedAge - lastTime;\n\t\t float age = offsetTime / (time - lastTime);\n currentValue = mix(lastValue, key.y, age);\n\t\t cumulativeValue += (lastValue + currentValue) * 0.5 * offsetTime;\n\t\t break;\n\t\t}\n\t else{\n\t\t cumulativeValue += (lastValue + key.y) * 0.5 * (time - lastKey.x);\n\t\t}\n\t}\n return cumulativeValue;\n}\n\nvec4 evaluateParticleGradient(in vec4 colorKeys[4], in float colorMaxTime, in vec2 alphaKeys[4], in float alphaMaxTime, in float t) {\n vec4 value;\n\n float alphaT = min(t, alphaMaxTime);\n for (int i = 0; i < 4; i++) {\n vec2 key = alphaKeys[i];\n if (alphaT <= key.x) {\n if (i == 0) {\n value.a = alphaKeys[0].y;\n } else {\n vec2 lastKey = alphaKeys[i - 1];\n float age = (alphaT - lastKey.x) / (key.x - lastKey.x);\n value.a = mix(lastKey.y, key.y, age);\n }\n break;\n }\n }\n\n float colorT = min(t, colorMaxTime);\n for (int i = 0; i < 4; i++) {\n vec4 key = colorKeys[i];\n if (colorT <= key.x) {\n if (i == 0) {\n value.rgb = colorKeys[0].yzw;\n } else {\n vec4 lastKey = colorKeys[i - 1];\n float age = (colorT - lastKey.x) / (key.x - lastKey.x);\n value.rgb = mix(lastKey.yzw, key.yzw, age);\n }\n break;\n }\n }\n\n return value;\n}"; // eslint-disable-line
4884
-
4885
- var velocity_over_lifetime_module = "#if defined(RENDERER_VOL_CONSTANT_MODE) || defined(RENDERER_VOL_CURVE_MODE)\n #define _VOL_MODULE_ENABLED\n#endif\n\n#ifdef _VOL_MODULE_ENABLED\n uniform int renderer_VOLSpace;\n\n #ifdef RENDERER_VOL_CONSTANT_MODE\n uniform vec3 renderer_VOLMaxConst;\n\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n uniform vec3 renderer_VOLMinConst;\n #endif\n #endif\n\n #ifdef RENDERER_VOL_CURVE_MODE\n uniform vec2 renderer_VOLMaxGradientX[4]; // x:time y:value\n uniform vec2 renderer_VOLMaxGradientY[4]; // x:time y:value\n uniform vec2 renderer_VOLMaxGradientZ[4]; // x:time y:value\n\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n uniform vec2 renderer_VOLMinGradientX[4]; // x:time y:value\n uniform vec2 renderer_VOLMinGradientY[4]; // x:time y:value\n uniform vec2 renderer_VOLMinGradientZ[4]; // x:time y:value\n #endif\n #endif\n\n\n vec3 computeVelocityPositionOffset(in float normalizedAge, in float age, out vec3 currentVelocity) {\n vec3 velocityPosition;\n\n #ifdef RENDERER_VOL_CONSTANT_MODE\n currentVelocity = renderer_VOLMaxConst;\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n currentVelocity = mix(renderer_VOLMinConst, currentVelocity, a_Random1.yzw);\n #endif\n\n velocityPosition = currentVelocity * age;\n #endif\n\n #ifdef RENDERER_VOL_CURVE_MODE\n velocityPosition = vec3(\n evaluateParticleCurveCumulative(renderer_VOLMaxGradientX, normalizedAge, currentVelocity.x),\n evaluateParticleCurveCumulative(renderer_VOLMaxGradientY, normalizedAge, currentVelocity.y),\n evaluateParticleCurveCumulative(renderer_VOLMaxGradientZ, normalizedAge, currentVelocity.z));\n\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n vec3 minCurrentVelocity;\n vec3 minVelocityPosition = vec3(\n evaluateParticleCurveCumulative(renderer_VOLMinGradientX, normalizedAge, minCurrentVelocity.x),\n evaluateParticleCurveCumulative(renderer_VOLMinGradientY, normalizedAge, minCurrentVelocity.y),\n evaluateParticleCurveCumulative(renderer_VOLMinGradientZ, normalizedAge, minCurrentVelocity.z));\n\n currentVelocity = mix(minCurrentVelocity, currentVelocity, a_Random1.yzw);\n velocityPosition = mix(minVelocityPosition, velocityPosition, a_Random1.yzw);\n #endif\n\n velocityPosition *= vec3(a_ShapePositionStartLifeTime.w);\n #endif\n return velocityPosition;\n }\n#endif\n"; // eslint-disable-line
4886
-
4887
- var rotation_over_lifetime_module = "#if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n #ifdef RENDERER_ROL_CURVE_MODE\n uniform vec2 renderer_ROLMaxCurveZ[4];\n #ifdef RENDERER_ROL_IS_SEPARATE\n uniform vec2 renderer_ROLMaxCurveX[4];\n uniform vec2 renderer_ROLMaxCurveY[4];\n #endif\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n uniform vec2 renderer_ROLMinCurveZ[4];\n #ifdef RENDERER_ROL_IS_SEPARATE\n uniform vec2 renderer_ROLMinCurveX[4];\n uniform vec2 renderer_ROLMinCurveY[4];\n #endif\n #endif\n #else\n uniform vec3 renderer_ROLMaxConst;\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n uniform vec3 renderer_ROLMinConst;\n #endif\n #endif\n#endif\n\nfloat computeParticleRotationFloat(in float rotation, in float age, in float normalizedAge) {\n #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n #ifdef RENDERER_ROL_CURVE_MODE\n float currentValue;\n float lifeRotation = evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue);\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n lifeRotation = mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveZ, normalizedAge, currentValue), lifeRotation, a_Random0.w);\n #endif\n rotation += lifeRotation * a_ShapePositionStartLifeTime.w;\n #else\n float lifeRotation = renderer_ROLMaxConst.z;\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n lifeRotation = mix(renderer_ROLMinConst.z, lifeRotation, a_Random0.w);\n #endif\n rotation += lifeRotation * age;\n #endif\n #endif\n return rotation;\n}\n\n\n#if defined(RENDERER_MODE_MESH) && (defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE))\nvec3 computeParticleRotationVec3(in vec3 rotation, in float age, in float normalizedAge) {\n #ifdef RENDERER_ROL_IS_SEPARATE\n #ifdef RENDERER_ROL_CONSTANT_MODE\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n vec3 ageRot = mix(renderer_ROLMinConst, renderer_ROLMaxConst, a_Random0.w) * age;\n #else\n vec3 ageRot = renderer_ROLMaxConst * age;\n #endif\n rotation += ageRot;\n #endif\n #ifdef RENDERER_ROL_CURVE_MODE\n float currentValue;\n float lifetime = a_ShapePositionStartLifeTime.w;\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n rotation += vec3(\n mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveX, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveX, normalizedAge, currentValue), a_Random0.w),\n mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveY, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveY, normalizedAge, currentValue), a_Random0.w),\n mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveZ, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue), a_Random0.w)) * lifetime;\n #else\n rotation += vec3(\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveX, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveY, normalizedAge, currentValue),\n evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue)) * lifetime;\n #endif\n #endif\n #else\n #ifdef RENDERER_ROL_CONSTANT_MODE\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n float ageRot = mix(renderer_ROLMinConst.z, renderer_ROLMaxConst.z, a_Random0.w) * age;\n #else\n float ageRot = renderer_ROLMaxConst.z * age;\n #endif\n rotation += ageRot;\n #endif\n\n #ifdef RENDERER_ROL_CURVE_MODE\n float currentValue;\n float lifeRotation = evaluateParticleCurveCumulative(renderer_ROLMaxCurveZ, normalizedAge, currentValue);\n #ifdef RENDERER_ROL_IS_RANDOM_TWO\n lifeRotation = mix(evaluateParticleCurveCumulative(renderer_ROLMinCurveZ, normalizedAge, currentValue), lifeRotation, a_Random0.w);\n #endif\n rotation += lifeRotation * a_ShapePositionStartLifeTime.w;\n #endif\n #endif\n return rotation;\n}\n#endif\n"; // eslint-disable-line
4888
-
4889
- var size_over_lifetime_module = "#ifdef RENDERER_SOL_CURVE_MODE\n uniform vec2 renderer_SOLMaxCurveX[4]; // x:time y:value\n #ifdef RENDERER_SOL_IS_SEPARATE\n uniform vec2 renderer_SOLMaxCurveY[4]; // x:time y:value\n uniform vec2 renderer_SOLMaxCurveZ[4]; // x:time y:value\n #endif\n\n #ifdef RENDERER_SOL_IS_RANDOM_TWO\n uniform vec2 renderer_SOLMinCurveX[4]; // x:time y:value\n #ifdef RENDERER_SOL_IS_SEPARATE\n uniform vec2 renderer_SOLMinCurveY[4]; // x:time y:value\n uniform vec2 renderer_SOLMinCurveZ[4]; // x:time y:value\n #endif\n #endif\n#endif\n\nvec2 computeParticleSizeBillboard(in vec2 size, in float normalizedAge) {\n #ifdef RENDERER_SOL_CURVE_MODE\n float lifeSizeX = evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge);\n #ifdef RENDERER_SOL_IS_RANDOM_TWO\n lifeSizeX = mix(evaluateParticleCurve(renderer_SOLMinCurveX, normalizedAge), lifeSizeX, a_Random0.z);\n #endif\n\n #ifdef RENDERER_SOL_IS_SEPARATE\n float lifeSizeY = evaluateParticleCurve(renderer_SOLMaxCurveY, normalizedAge);\n #ifdef RENDERER_SOL_IS_RANDOM_TWO\n lifeSizeY = mix(evaluateParticleCurve(renderer_SOLMinCurveY, normalizedAge), lifeSizeY, a_Random0.z);\n #endif\n size *= vec2(lifeSizeX, lifeSizeY);\n #else\n size *= lifeSizeX;\n #endif\n #endif\n return size;\n}\n\n#ifdef RENDERER_MODE_MESH\n vec3 computeParticleSizeMesh(in vec3 size, in float normalizedAge) {\n #ifdef RENDERER_SOL_CURVE\n size *= evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge);\n #endif\n #ifdef RENDERER_SOL_RANDOM_CURVES\n size *= mix(evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge),\n evaluateParticleCurve(u_SOLSizeGradientMax, normalizedAge),\n a_Random0.z);\n #endif\n #ifdef RENDERER_SOL_CURVE_SEPARATE\n size *= vec3(evaluateParticleCurve(renderer_SOLMinCurveX, normalizedAge),\n evaluateParticleCurve(renderer_SOLMinCurveY, normalizedAge),\n evaluateParticleCurve(renderer_SOLMinCurveZ, normalizedAge));\n #endif\n #ifdef RENDERER_SOL_RANDOM_CURVES_SEPARATE\n size *= vec3(mix(evaluateParticleCurve(renderer_SOLMinCurveX, normalizedAge),\n evaluateParticleCurve(renderer_SOLMaxCurveX, normalizedAge),\n a_Random0.z),\n mix(evaluateParticleCurve(renderer_SOLMinCurveY, normalizedAge),\n evaluateParticleCurve(renderer_SOLMaxCurveY, normalizedAge),\n a_Random0.z),\n mix(evaluateParticleCurve(renderer_SOLMinCurveZ, normalizedAge),\n evaluateParticleCurve(renderer_SOLMaxCurveZ, normalizedAge),\n a_Random0.z));\n #endif\n return size;\n }\n#endif"; // eslint-disable-line
4890
-
4891
- var color_over_lifetime_module = "#if defined(RENDERER_COL_GRADIENT) || defined(RENDERER_COL_RANDOM_GRADIENTS)\n uniform vec4 renderer_COLMaxGradientColor[4]; // x:time y:r z:g w:b\n uniform vec2 renderer_COLMaxGradientAlpha[4]; // x:time y:alpha\n\n #ifdef RENDERER_COL_RANDOM_GRADIENTS\n uniform vec4 renderer_COLMinGradientColor[4]; // x:time y:r z:g w:b\n uniform vec2 renderer_COLMinGradientAlpha[4]; // x:time y:alpha\n #endif\n\n uniform vec4 renderer_COLGradientKeysMaxTime; // x: minColorKeysMaxTime, y: minAlphaKeysMaxTime, z: maxColorKeysMaxTime, w: maxAlphaKeysMaxTime\n#endif\n\n\nvec4 computeParticleColor(in vec4 color, in float normalizedAge) {\n #if defined(RENDERER_COL_GRADIENT) || defined(RENDERER_COL_RANDOM_GRADIENTS)\n vec4 gradientColor = evaluateParticleGradient(renderer_COLMaxGradientColor, renderer_COLGradientKeysMaxTime.z, renderer_COLMaxGradientAlpha, renderer_COLGradientKeysMaxTime.w, normalizedAge);\n #endif\n\n #ifdef RENDERER_COL_RANDOM_GRADIENTS\n gradientColor = mix(evaluateParticleGradient(renderer_COLMinGradientColor,renderer_COLGradientKeysMaxTime.x, renderer_COLMinGradientAlpha, renderer_COLGradientKeysMaxTime.y, normalizedAge), gradientColor, a_Random0.y);\n #endif\n\n #if defined(RENDERER_COL_GRADIENT) || defined(RENDERER_COL_RANDOM_GRADIENTS)\n color *= gradientColor;\n #endif\n\n return color;\n}\n"; // eslint-disable-line
4892
-
4893
- var texture_sheet_animation_module = "#if defined(RENDERER_TSA_FRAME_CURVE) || defined(RENDERER_TSA_FRAME_RANDOM_CURVES)\n uniform float renderer_TSACycles;\n uniform vec3 renderer_TSATillingParams; // x:subU y:subV z:tileCount\n uniform vec2 renderer_TSAFrameMaxCurve[4]; // x:time y:value\n\n #ifdef RENDERER_TSA_FRAME_RANDOM_CURVES\n uniform vec2 renderer_TSAFrameMinCurve[4]; // x:time y:value\n #endif\n#endif\n\nvec2 computeParticleUV(in vec2 uv, in float normalizedAge) {\n #if defined(RENDERER_TSA_FRAME_CURVE) || defined(RENDERER_TSA_FRAME_RANDOM_CURVES)\n float scaledNormalizedAge = normalizedAge * renderer_TSACycles;\n float cycleNormalizedAge = scaledNormalizedAge - floor(scaledNormalizedAge);\n float normalizedFrame = evaluateParticleCurve(renderer_TSAFrameMaxCurve, cycleNormalizedAge);\n #ifdef RENDERER_TSA_FRAME_RANDOM_CURVES\n normalizedFrame = mix(evaluateParticleCurve(renderer_TSAFrameMinCurve, cycleNormalizedAge), normalizedFrame, a_Random1.x);\n #endif\n\n float frame = floor(normalizedFrame * renderer_TSATillingParams.z);\n\n float tileRow = frame * renderer_TSATillingParams.x;\n float tileRowIndex = floor(tileRow);\n uv.x += tileRow - tileRowIndex;\n uv.y += tileRowIndex * renderer_TSATillingParams.y;\n #endif\n \n return uv;\n}\n"; // eslint-disable-line
4894
-
4895
- var force_over_lifetime_module = "#if defined(RENDERER_FOL_CONSTANT_MODE) || defined(RENDERER_FOL_CURVE_MODE)\n #define _FOL_MODULE_ENABLED\n#endif\n\n#ifdef _FOL_MODULE_ENABLED\n uniform int renderer_FOLSpace;\n\n #ifdef RENDERER_FOL_CONSTANT_MODE\n uniform vec3 renderer_FOLMaxConst;\n\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n uniform vec3 renderer_FOLMinConst;\n #endif\n\n #endif\n\n #ifdef RENDERER_FOL_CURVE_MODE\n uniform vec2 renderer_FOLMaxGradientX[4];\n uniform vec2 renderer_FOLMaxGradientY[4];\n uniform vec2 renderer_FOLMaxGradientZ[4];\n\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n uniform vec2 renderer_FOLMinGradientX[4];\n uniform vec2 renderer_FOLMinGradientY[4];\n uniform vec2 renderer_FOLMinGradientZ[4];\n #endif\n #endif\n\n // (tHat - t1) * (tHat - t1) * (tHat - t1) * (a2 - a1) / ((t2 - t1) * 6.0) + a1 * (tHat - t1) * (tHat - t1) * 0.5 + v1 * (tHat - t1);\n // to = tHat - t1; tr = t2 - t1\n float computeDisplacementIntegral(in float to, in float tr, in float a1, in float a2, in float v1) {\n return to * to * to * (a2 - a1) / (tr * 6.0) + a1 * to * to * 0.5 + v1 * to;\n }\n\n float evaluateForceParticleCurveCumulative(in vec2 keys[4], in float normalizedAge, out float velocityCumulative) {\n float cumulativeValue = 0.0;\n velocityCumulative = 0.0;\n\n for (int i = 1; i < 4; i++){\n vec2 key = keys[i];\n vec2 lastKey = keys[i - 1];\n float timeRange = (key.x - lastKey.x) * a_ShapePositionStartLifeTime.w;\n\n if (key.x >= normalizedAge){\n float timeOffset = (normalizedAge - lastKey.x) * a_ShapePositionStartLifeTime.w;\n cumulativeValue += computeDisplacementIntegral(timeOffset, timeRange, lastKey.y, key.y, velocityCumulative);\n\n float finalAcceleration = mix(lastKey.y, key.y, timeOffset / timeRange);\n velocityCumulative += 0.5 * timeOffset * (finalAcceleration + lastKey.y);\n break;\n } else { \n cumulativeValue += computeDisplacementIntegral(timeRange, timeRange, lastKey.y, key.y, velocityCumulative);\n velocityCumulative += 0.5 * timeRange * (lastKey.y + key.y);\n }\n }\n return cumulativeValue;\n }\n\n vec3 computeForcePositionOffset(in float normalizedAge, in float age, out vec3 velocityOffset) {\n vec3 forcePosition;\n\n #if defined(RENDERER_FOL_CONSTANT_MODE)\n vec3 forceAcceleration = renderer_FOLMaxConst;\n\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n forceAcceleration = mix(renderer_FOLMinConst, forceAcceleration, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n\n velocityOffset = forceAcceleration * age;\n\n forcePosition = 0.5 * forceAcceleration * age * age;\n #elif defined(RENDERER_FOL_CURVE_MODE)\n forcePosition = vec3(\n evaluateForceParticleCurveCumulative(renderer_FOLMaxGradientX, normalizedAge, velocityOffset.x),\n evaluateForceParticleCurveCumulative(renderer_FOLMaxGradientY, normalizedAge, velocityOffset.y),\n evaluateForceParticleCurveCumulative(renderer_FOLMaxGradientZ, normalizedAge, velocityOffset.z)\n );\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n vec3 minVelocityOffset;\n\n forcePosition = vec3(\n mix(evaluateForceParticleCurveCumulative(renderer_FOLMinGradientX, normalizedAge, minVelocityOffset.x), forcePosition.x, a_Random2.x),\n mix(evaluateForceParticleCurveCumulative(renderer_FOLMinGradientY, normalizedAge, minVelocityOffset.y), forcePosition.y, a_Random2.y),\n mix(evaluateForceParticleCurveCumulative(renderer_FOLMinGradientZ, normalizedAge, minVelocityOffset.z), forcePosition.z, a_Random2.z)\n );\n\n velocityOffset = mix(minVelocityOffset, velocityOffset, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n #endif\n return forcePosition;\n }\n#endif"; // eslint-disable-line
4896
-
4897
- var limit_velocity_over_lifetime_module = "#ifdef RENDERER_LVL_MODULE_ENABLED\n uniform int renderer_LVLSpace;\n uniform float renderer_LVLDampen;\n\n // Scalar limit\n #ifndef RENDERER_LVL_SEPARATE_AXES\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n uniform float renderer_LVLSpeedMaxConst;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform float renderer_LVLSpeedMinConst;\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n uniform vec2 renderer_LVLSpeedMaxCurve[4];\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform vec2 renderer_LVLSpeedMinCurve[4];\n #endif\n #endif\n #endif\n\n // Per-axis limit\n #ifdef RENDERER_LVL_SEPARATE_AXES\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n uniform vec3 renderer_LVLSpeedMaxConstVector;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform vec3 renderer_LVLSpeedMinConstVector;\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n uniform vec2 renderer_LVLSpeedXMaxCurve[4];\n uniform vec2 renderer_LVLSpeedYMaxCurve[4];\n uniform vec2 renderer_LVLSpeedZMaxCurve[4];\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n uniform vec2 renderer_LVLSpeedXMinCurve[4];\n uniform vec2 renderer_LVLSpeedYMinCurve[4];\n uniform vec2 renderer_LVLSpeedZMinCurve[4];\n #endif\n #endif\n #endif\n\n // Drag curve\n #ifdef RENDERER_LVL_DRAG_CURVE_MODE\n uniform vec2 renderer_LVLDragMaxCurve[4];\n #ifdef RENDERER_LVL_DRAG_IS_RANDOM_TWO\n uniform vec2 renderer_LVLDragMinCurve[4];\n #endif\n #endif\n\n float evaluateLVLDrag(float normalizedAge, float dragRand) {\n #ifdef RENDERER_LVL_DRAG_CURVE_MODE\n float dragMax = evaluateParticleCurve(renderer_LVLDragMaxCurve, normalizedAge);\n #ifdef RENDERER_LVL_DRAG_IS_RANDOM_TWO\n float dragMin = evaluateParticleCurve(renderer_LVLDragMinCurve, normalizedAge);\n return mix(dragMin, dragMax, dragRand);\n #else\n return dragMax;\n #endif\n #else\n return mix(renderer_LVLDragConstant.x, renderer_LVLDragConstant.y, dragRand);\n #endif\n }\n\n vec3 applyLVLSpeedLimitTF(vec3 velocity, float normalizedAge, float limitRand, float effectiveDampen) {\n #ifdef RENDERER_LVL_SEPARATE_AXES\n vec3 limitSpeed;\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n limitSpeed = renderer_LVLSpeedMaxConstVector;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n limitSpeed = mix(renderer_LVLSpeedMinConstVector, limitSpeed, limitRand);\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n limitSpeed = vec3(\n evaluateParticleCurve(renderer_LVLSpeedXMaxCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedYMaxCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedZMaxCurve, normalizedAge)\n );\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n vec3 minLimitSpeed = vec3(\n evaluateParticleCurve(renderer_LVLSpeedXMinCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedYMinCurve, normalizedAge),\n evaluateParticleCurve(renderer_LVLSpeedZMinCurve, normalizedAge)\n );\n limitSpeed = mix(minLimitSpeed, limitSpeed, limitRand);\n #endif\n #endif\n\n vec3 absVel = abs(velocity);\n vec3 excess = max(absVel - limitSpeed, vec3(0.0));\n velocity = sign(velocity) * (absVel - excess * effectiveDampen);\n #else\n float limitSpeed;\n #ifdef RENDERER_LVL_SPEED_CONSTANT_MODE\n limitSpeed = renderer_LVLSpeedMaxConst;\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n limitSpeed = mix(renderer_LVLSpeedMinConst, limitSpeed, limitRand);\n #endif\n #endif\n #ifdef RENDERER_LVL_SPEED_CURVE_MODE\n limitSpeed = evaluateParticleCurve(renderer_LVLSpeedMaxCurve, normalizedAge);\n #ifdef RENDERER_LVL_SPEED_IS_RANDOM_TWO\n float minLimitSpeed = evaluateParticleCurve(renderer_LVLSpeedMinCurve, normalizedAge);\n limitSpeed = mix(minLimitSpeed, limitSpeed, limitRand);\n #endif\n #endif\n\n float speed = length(velocity);\n if (speed > limitSpeed && speed > 0.0) {\n float excess = speed - limitSpeed;\n velocity = velocity * ((speed - excess * effectiveDampen) / speed);\n }\n #endif\n return velocity;\n }\n\n#endif\n"; // eslint-disable-line
4898
-
4899
- var noise_module = "#ifdef RENDERER_NOISE_MODULE_ENABLED\n\n#include <noise_common>\n#include <noise_simplex_3D_grad>\n\nuniform vec4 renderer_NoiseParams; // xyz = strength (constant mode only), w = frequency\nuniform vec4 renderer_NoiseOctaveParams; // x = scrollSpeed, y = octaveCount, z = octaveIntensityMultiplier, w = octaveFrequencyMultiplier\n\n#ifdef RENDERER_NOISE_STRENGTH_CURVE\n uniform vec2 renderer_NoiseStrengthMaxCurveX[4];\n #ifdef RENDERER_NOISE_IS_SEPARATE\n uniform vec2 renderer_NoiseStrengthMaxCurveY[4];\n uniform vec2 renderer_NoiseStrengthMaxCurveZ[4];\n #endif\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n uniform vec2 renderer_NoiseStrengthMinCurveX[4];\n #ifdef RENDERER_NOISE_IS_SEPARATE\n uniform vec2 renderer_NoiseStrengthMinCurveY[4];\n uniform vec2 renderer_NoiseStrengthMinCurveZ[4];\n #endif\n #endif\n#else\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n uniform vec3 renderer_NoiseStrengthMinConst;\n #endif\n#endif\n\nvec3 sampleCurlNoise3D(vec3 coord) {\n float axisOffset = 100.0;\n vec3 gradX = simplexGrad(vec3(coord.z, coord.y, coord.x));\n vec3 gradY = simplexGrad(vec3(coord.x + axisOffset, coord.z, coord.y));\n vec3 gradZ = simplexGrad(vec3(coord.y, coord.x + axisOffset, coord.z));\n return vec3(\n gradZ.x - gradY.y,\n gradX.x - gradZ.y,\n gradY.x - gradX.y\n );\n}\n\nvec3 computeNoiseVelocity(vec3 currentPosition, float normalizedAge) {\n vec3 coord = currentPosition * renderer_NoiseParams.w\n + vec3(renderer_CurrentTime * renderer_NoiseOctaveParams.x);\n\n int octaveCount = int(renderer_NoiseOctaveParams.y);\n float octaveIntensityMultiplier = renderer_NoiseOctaveParams.z;\n float octaveFrequencyMultiplier = renderer_NoiseOctaveParams.w;\n\n vec3 noiseValue = sampleCurlNoise3D(coord);\n float totalAmplitude = 1.0;\n\n // Unrolled octave loop (GLSL ES 1.0 requires constant loop bounds)\n if (octaveCount >= 2) {\n float amplitude = octaveIntensityMultiplier;\n totalAmplitude += amplitude;\n noiseValue += amplitude * sampleCurlNoise3D(coord * octaveFrequencyMultiplier);\n\n if (octaveCount >= 3) {\n amplitude *= octaveIntensityMultiplier;\n totalAmplitude += amplitude;\n noiseValue += amplitude * sampleCurlNoise3D(coord * octaveFrequencyMultiplier * octaveFrequencyMultiplier);\n }\n }\n\n // Evaluate strength (supports Constant, TwoConstants, Curve, TwoCurves).\n vec3 strength;\n #ifdef RENDERER_NOISE_STRENGTH_CURVE\n float sx = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveX, normalizedAge);\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n sx = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveX, normalizedAge), sx, a_Random0.z);\n #endif\n #ifdef RENDERER_NOISE_IS_SEPARATE\n float sy = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveY, normalizedAge);\n float sz = evaluateParticleCurve(renderer_NoiseStrengthMaxCurveZ, normalizedAge);\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n sy = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveY, normalizedAge), sy, a_Random0.z);\n sz = mix(evaluateParticleCurve(renderer_NoiseStrengthMinCurveZ, normalizedAge), sz, a_Random0.z);\n #endif\n strength = vec3(sx, sy, sz);\n #else\n strength = vec3(sx);\n #endif\n #else\n strength = renderer_NoiseParams.xyz;\n #ifdef RENDERER_NOISE_STRENGTH_IS_RANDOM_TWO\n strength = mix(renderer_NoiseStrengthMinConst, strength, a_Random0.z);\n #endif\n #endif\n\n return (noiseValue / totalAmplitude) * strength;\n}\n\n#endif\n"; // eslint-disable-line
4900
-
4901
- var particle_feedback_simulation = "// Transform Feedback update shader for particle simulation.\n// Update order: VOL/FOL → Dampen → Drag → Position.\n// Runs once per particle per frame (no rasterization).\n\n// Previous frame TF data\nattribute vec3 a_FeedbackPosition;\nattribute vec3 a_FeedbackVelocity;\n\n// Per-particle instance data\nattribute vec4 a_ShapePositionStartLifeTime;\nattribute vec4 a_DirectionTime;\nattribute vec3 a_StartSize;\nattribute float a_StartSpeed;\nattribute vec4 a_Random0;\nattribute vec4 a_Random1;\nattribute vec3 a_SimulationWorldPosition;\nattribute vec4 a_SimulationWorldRotation;\nattribute vec4 a_Random2;\n\n// Uniforms\nuniform float renderer_CurrentTime;\nuniform float renderer_DeltaTime;\nuniform vec3 renderer_Gravity;\nuniform vec2 renderer_LVLDragConstant;\nuniform vec3 renderer_WorldPosition;\nuniform vec4 renderer_WorldRotation;\nuniform int renderer_SimulationSpace;\n\n// TF outputs\nvarying vec3 v_FeedbackPosition;\nvarying vec3 v_FeedbackVelocity;\n\n#include <particle_common>\n#include <velocity_over_lifetime_module>\n#include <force_over_lifetime_module>\n#include <limit_velocity_over_lifetime_module>\n#include <noise_module>\n\n// Get VOL instantaneous velocity at normalizedAge\nvec3 getVOLVelocity(float normalizedAge) {\n vec3 vel = vec3(0.0);\n #ifdef _VOL_MODULE_ENABLED\n #ifdef RENDERER_VOL_CONSTANT_MODE\n vel = renderer_VOLMaxConst;\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n vel = mix(renderer_VOLMinConst, vel, a_Random1.yzw);\n #endif\n #endif\n #ifdef RENDERER_VOL_CURVE_MODE\n vel = vec3(\n evaluateParticleCurve(renderer_VOLMaxGradientX, normalizedAge),\n evaluateParticleCurve(renderer_VOLMaxGradientY, normalizedAge),\n evaluateParticleCurve(renderer_VOLMaxGradientZ, normalizedAge)\n );\n #ifdef RENDERER_VOL_IS_RANDOM_TWO\n vec3 minVel = vec3(\n evaluateParticleCurve(renderer_VOLMinGradientX, normalizedAge),\n evaluateParticleCurve(renderer_VOLMinGradientY, normalizedAge),\n evaluateParticleCurve(renderer_VOLMinGradientZ, normalizedAge)\n );\n vel = mix(minVel, vel, a_Random1.yzw);\n #endif\n #endif\n #endif\n return vel;\n}\n\n// Get FOL instantaneous acceleration at normalizedAge\nvec3 getFOLAcceleration(float normalizedAge) {\n vec3 acc = vec3(0.0);\n #ifdef _FOL_MODULE_ENABLED\n #ifdef RENDERER_FOL_CONSTANT_MODE\n acc = renderer_FOLMaxConst;\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n acc = mix(renderer_FOLMinConst, acc, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n #endif\n #ifdef RENDERER_FOL_CURVE_MODE\n acc = vec3(\n evaluateParticleCurve(renderer_FOLMaxGradientX, normalizedAge),\n evaluateParticleCurve(renderer_FOLMaxGradientY, normalizedAge),\n evaluateParticleCurve(renderer_FOLMaxGradientZ, normalizedAge)\n );\n #ifdef RENDERER_FOL_IS_RANDOM_TWO\n vec3 minAcc = vec3(\n evaluateParticleCurve(renderer_FOLMinGradientX, normalizedAge),\n evaluateParticleCurve(renderer_FOLMinGradientY, normalizedAge),\n evaluateParticleCurve(renderer_FOLMinGradientZ, normalizedAge)\n );\n acc = mix(minAcc, acc, vec3(a_Random2.x, a_Random2.y, a_Random2.z));\n #endif\n #endif\n #endif\n return acc;\n}\n\nvoid main() {\n float age = renderer_CurrentTime - a_DirectionTime.w;\n float lifetime = a_ShapePositionStartLifeTime.w;\n float normalizedAge = age / lifetime;\n // Clamp to age on the first TF pass: particles emitted mid-frame have age < dt,\n // so using the full dt would over-integrate. Subsequent passes are unaffected (age >= dt).\n float dt = min(renderer_DeltaTime, age);\n\n // normalizedAge < 0.0: stale TF slot whose startTime is from a previous playback (e.g. after StopEmittingAndClear).\n if (normalizedAge >= 1.0 || normalizedAge < 0.0) {\n v_FeedbackPosition = a_FeedbackPosition;\n v_FeedbackVelocity = a_FeedbackVelocity;\n gl_Position = vec4(0.0);\n return;\n }\n\n vec4 worldRotation;\n if (renderer_SimulationSpace == 0) {\n worldRotation = renderer_WorldRotation;\n } else {\n worldRotation = a_SimulationWorldRotation;\n }\n vec4 invWorldRotation = quaternionConjugate(worldRotation);\n\n // Read previous frame state (initialized by CPU on particle birth)\n vec3 localVelocity = a_FeedbackVelocity;\n\n // =====================================================\n // Step 1: Apply velocity module deltas (VOL + FOL + Gravity)\n // =====================================================\n\n // Gravity (world space)\n vec3 gravityDelta = renderer_Gravity * a_Random0.x * dt;\n\n // VOL instantaneous velocity (animated velocity, not persisted)\n vec3 volLocal = vec3(0.0);\n vec3 volWorld = vec3(0.0);\n #ifdef _VOL_MODULE_ENABLED\n vec3 vol = getVOLVelocity(normalizedAge);\n if (renderer_VOLSpace == 0) {\n volLocal = vol;\n } else {\n volWorld = vol;\n }\n #endif\n\n // FOL acceleration → velocity delta (always persisted, like gravity)\n vec3 folDeltaLocal = vec3(0.0);\n #ifdef _FOL_MODULE_ENABLED\n vec3 folAcc = getFOLAcceleration(normalizedAge);\n vec3 folVelDelta = folAcc * dt;\n if (renderer_FOLSpace == 0) {\n folDeltaLocal = folVelDelta;\n } else {\n // World FOL: convert to local and persist, same as gravity\n folDeltaLocal = rotationByQuaternions(folVelDelta, invWorldRotation);\n }\n #endif\n\n // Gravity and FOL contribute to base velocity (persisted, subject to dampen/drag).\n vec3 gravityLocal = rotationByQuaternions(gravityDelta, invWorldRotation);\n localVelocity += folDeltaLocal + gravityLocal;\n\n // =====================================================\n // Step 2 & 3: Dampen (Limit Velocity) + Drag\n // VOL must be projected into the LVL target space so that\n // limit/drag see the full velocity regardless of VOL.space vs LVL.space.\n // =====================================================\n #ifdef RENDERER_LVL_MODULE_ENABLED\n // Precompute VOL in both spaces\n vec3 volAsLocal = volLocal + rotationByQuaternions(volWorld, invWorldRotation);\n vec3 volAsWorld = rotationByQuaternions(volLocal, worldRotation) + volWorld;\n\n float limitRand = a_Random2.w;\n float dampen = renderer_LVLDampen;\n // Frame-rate independent dampen (30fps as reference)\n float effectiveDampen = 1.0 - pow(1.0 - dampen, dt * 30.0);\n\n if (renderer_LVLSpace == 0) {\n // Local space: total = base + all VOL projected to local\n vec3 totalLocal = localVelocity + volAsLocal;\n vec3 dampenedTotal = applyLVLSpeedLimitTF(totalLocal, normalizedAge, limitRand, effectiveDampen);\n localVelocity = dampenedTotal - volAsLocal;\n } else {\n // World space: total = rotated base + all VOL projected to world\n vec3 totalWorld = rotationByQuaternions(localVelocity, worldRotation) + volAsWorld;\n vec3 dampenedTotal = applyLVLSpeedLimitTF(totalWorld, normalizedAge, limitRand, effectiveDampen);\n localVelocity = rotationByQuaternions(dampenedTotal - volAsWorld, invWorldRotation);\n }\n\n // Drag: same space as dampen\n {\n float dragCoeff = evaluateLVLDrag(normalizedAge, a_Random2.w);\n if (dragCoeff > 0.0) {\n vec3 totalVel;\n if (renderer_LVLSpace == 0) {\n totalVel = localVelocity + volAsLocal;\n } else {\n totalVel = rotationByQuaternions(localVelocity, worldRotation) + volAsWorld;\n }\n float velMagSqr = dot(totalVel, totalVel);\n float velMag = sqrt(velMagSqr);\n\n float drag = dragCoeff;\n\n #ifdef RENDERER_LVL_DRAG_MULTIPLY_SIZE\n float maxDim = max(a_StartSize.x, max(a_StartSize.y, a_StartSize.z));\n float radius = maxDim * 0.5;\n drag *= 3.14159265 * radius * radius;\n #endif\n\n #ifdef RENDERER_LVL_DRAG_MULTIPLY_VELOCITY\n drag *= velMagSqr;\n #endif\n\n if (velMag > 0.0) {\n float newVelMag = max(0.0, velMag - drag * dt);\n vec3 draggedTotal = totalVel * (newVelMag / velMag);\n if (renderer_LVLSpace == 0) {\n localVelocity = draggedTotal - volAsLocal;\n } else {\n localVelocity = rotationByQuaternions(draggedTotal - volAsWorld, invWorldRotation);\n }\n }\n }\n }\n #endif\n\n // =====================================================\n // Step 4: Integrate position in simulation space\n // Local mode: position in local space, velocity rotated to local\n // World mode: position in world space, velocity rotated to world\n // =====================================================\n // FOL is now fully in localVelocity (both local and world-space FOL).\n // VOL and Noise overlays are added here (not persisted).\n\n vec3 totalVelocity;\n if (renderer_SimulationSpace == 0) {\n totalVelocity = localVelocity + volLocal + rotationByQuaternions(volWorld, invWorldRotation);\n } else {\n totalVelocity = rotationByQuaternions(localVelocity + volLocal, worldRotation) + volWorld;\n }\n #ifdef RENDERER_NOISE_MODULE_ENABLED\n // Use analytical base position (birth + initial velocity * age) instead of\n // a_FeedbackPosition to avoid feedback loop: position → noise → velocity → position\n vec3 noiseBasePos;\n if (renderer_SimulationSpace == 0) {\n noiseBasePos = a_ShapePositionStartLifeTime.xyz + a_DirectionTime.xyz * a_StartSpeed * age;\n } else {\n noiseBasePos = rotationByQuaternions(\n a_ShapePositionStartLifeTime.xyz + a_DirectionTime.xyz * a_StartSpeed * age,\n worldRotation) + a_SimulationWorldPosition;\n }\n totalVelocity += computeNoiseVelocity(noiseBasePos, normalizedAge);\n #endif\n vec3 position = a_FeedbackPosition + totalVelocity * dt;\n\n v_FeedbackPosition = position;\n v_FeedbackVelocity = localVelocity;\n gl_Position = vec4(0.0);\n}\n"; // eslint-disable-line
4902
-
4903
- var sphere_billboard = "#ifdef RENDERER_MODE_SPHERE_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy;\n\tvec3 sideVector = normalize(cross(camera_Forward, camera_Up));\n\tvec3 upVector = normalize(cross(sideVector, camera_Forward));\n\tcorner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n if (renderer_ThreeDStartRotation) {\n vec3 rotation = radians(vec3(a_StartRotation0.xy, computeParticleRotationFloat(a_StartRotation0.z, age, normalizedAge)));\n center += renderer_SizeScale.xzy * rotationByEuler(corner.x * sideVector + corner.y * upVector, rotation);\n } else {\n float rot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation = mat2(c, -s, s, c);\n corner = rotation * corner;\n center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector);\n }\n #else\n if (renderer_ThreeDStartRotation) {\n center += renderer_SizeScale.xzy * rotationByEuler(corner.x * sideVector + corner.y * upVector, radians(a_StartRotation0));\n } else {\n float c = cos(radians(a_StartRotation0.x));\n float s = sin(radians(a_StartRotation0.x));\n mat2 rotation = mat2(c, -s, s, c);\n corner = rotation * corner;\n center += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector);\n }\n #endif\n#endif"; // eslint-disable-line
4904
-
4905
- var stretched_billboard = "#ifdef RENDERER_MODE_STRETCHED_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy;\n\tvec3 velocity = rotationByQuaternions(renderer_SizeScale * localVelocity, worldRotation) + worldVelocity;\n\tvec3 cameraUpVector = normalize(velocity);\n\tvec3 direction = normalize(center - camera_Position);\n\tvec3 sideVector = normalize(cross(direction, normalize(velocity)));\n\n\tsideVector = renderer_SizeScale.xzy * sideVector;\n\tcameraUpVector = length(vec3(renderer_SizeScale.x, 0.0, 0.0)) * cameraUpVector;\n\n\tvec2 size = computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n\n\tconst mat2 rotationZHalfPI = mat2(0.0, -1.0, 1.0, 0.0);\n\tcorner = rotationZHalfPI * corner;\n\tcorner.y = corner.y - abs(corner.y);\n\n\tfloat speed = length(velocity); // TODO:\n\tcenter += sign(renderer_SizeScale.x) * (sign(renderer_StretchedBillboardLengthScale) * size.x * corner.x * sideVector\n\t + (speed * renderer_StretchedBillboardSpeedScale + size.y * renderer_StretchedBillboardLengthScale) * corner.y * cameraUpVector);\n#endif"; // eslint-disable-line
4906
-
4907
- var vertical_billboard = "#ifdef RENDERER_MODE_VERTICAL_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy; // Billboard模式z轴无效\n\tconst vec3 cameraUpVector = vec3(0.0, 1.0, 0.0);\n\tvec3 sideVector = normalize(cross(camera_Forward, cameraUpVector));\n\n\tfloat rot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n\tfloat c = cos(rot);\n\tfloat s = sin(rot);\n\tmat2 rotation = mat2(c, -s, s, c);\n\tcorner = rotation * corner * cos(0.78539816339744830961566084581988); // TODO:临时缩小cos45,不确定U3D原因\n\tcorner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n\tcenter += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * cameraUpVector);\n#endif"; // eslint-disable-line
4908
-
4909
- var horizontal_billboard = "#ifdef RENDERER_MODE_HORIZONTAL_BILLBOARD\n\tvec2 corner = a_CornerTextureCoordinate.xy + renderer_PivotOffset.xy;\n\tconst vec3 sideVector = vec3(1.0, 0.0, 0.0);\n\tconst vec3 upVector = vec3(0.0, 0.0, -1.0);\n\tcorner *= computeParticleSizeBillboard(a_StartSize.xy, normalizedAge);\n\n\t// HorizontalBillboard rotates in XZ plane (around Y-axis normal).\n\t// Uses Z-axis rotation data to match Unity behavior.\n\tfloat rot;\n\tif (renderer_ThreeDStartRotation) {\n\t\trot = radians(computeParticleRotationFloat(a_StartRotation0.z, age, normalizedAge));\n\t} else {\n\t\trot = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n\t}\n\n\tfloat c = cos(rot);\n\tfloat s = sin(rot);\n\tmat2 rotation = mat2(c, -s, s, c);\n\tcorner = rotation * corner;\n\tcenter += renderer_SizeScale.xzy * (corner.x * sideVector + corner.y * upVector);\n#endif"; // eslint-disable-line
4910
-
4911
- var particle_mesh = "// Only support local alignment mode\n#ifdef RENDERER_MODE_MESH\n #if defined(RENDERER_ROL_CONSTANT_MODE) || defined(RENDERER_ROL_CURVE_MODE)\n #define RENDERER_ROL_ENABLED\n #endif\n\n\tvec3 size = computeParticleSizeMesh(a_StartSize, normalizedAge);\n\n bool is3DRotation = renderer_ThreeDStartRotation;\n #if defined(RENDERER_ROL_ENABLED) && defined(RENDERER_ROL_IS_SEPARATE)\n is3DRotation = true;\n #endif\n\n if (is3DRotation) {\n #ifdef RENDERER_ROL_ENABLED\n vec3 startRotation = renderer_ThreeDStartRotation ? a_StartRotation0 : vec3(0.0, 0.0, a_StartRotation0.x);\n vec3 rotation = radians(computeParticleRotationVec3(startRotation, age, normalizedAge));\n #else\n vec3 rotation = radians(a_StartRotation0);\n #endif\n // 3D Start Rotation is same in local and world simulation space\n center += rotationByQuaternions(renderer_SizeScale * rotationByEuler(POSITION * size, rotation), worldRotation);\n } else {\n #ifdef RENDERER_ROL_ENABLED\n float angle = radians(computeParticleRotationFloat(a_StartRotation0.x, age, normalizedAge));\n #else\n float angle = radians(a_StartRotation0.x);\n #endif\n #ifdef RENDERER_EMISSION_SHAPE\n // Axis is side vector of emit position look at zero\n vec3 axis = vec3(a_ShapePositionStartLifeTime.xy, 0.0);\n if (renderer_SimulationSpace == 1){\n axis = rotationByQuaternions(axis, worldRotation);\n }\n vec3 crossResult = cross(axis, vec3(0.0, 0.0, -1.0));\n float crossLen = length(crossResult);\n vec3 rotateAxis = crossLen > 0.0001 ? crossResult / crossLen : vec3(0.0, 1.0, 0.0);\n #else\n // Axis is negative z\n vec3 rotateAxis = vec3(0.0, 0.0, -1.0);\n #endif\n center += rotationByQuaternions(renderer_SizeScale *rotationByAxis(POSITION * size, rotateAxis, angle), worldRotation);\n }\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n\t\tv_MeshColor = COLOR_0;\n\t#endif\n#endif"; // eslint-disable-line
4912
-
4913
- var ParticleShaderLib = {
4914
- particle_common: particle_common,
4915
- velocity_over_lifetime_module: velocity_over_lifetime_module,
4916
- rotation_over_lifetime_module: rotation_over_lifetime_module,
4917
- size_over_lifetime_module: size_over_lifetime_module,
4918
- color_over_lifetime_module: color_over_lifetime_module,
4919
- texture_sheet_animation_module: texture_sheet_animation_module,
4920
- force_over_lifetime_module: force_over_lifetime_module,
4921
- limit_velocity_over_lifetime_module: limit_velocity_over_lifetime_module,
4922
- noise_module: noise_module,
4923
- particle_feedback_simulation: particle_feedback_simulation,
4924
- sphere_billboard: sphere_billboard,
4925
- stretched_billboard: stretched_billboard,
4926
- vertical_billboard: vertical_billboard,
4927
- horizontal_billboard: horizontal_billboard,
4928
- particle_mesh: particle_mesh
4929
- };
4930
-
4931
- var normal_get = "// gl_FrontFacing has random value on Adreno GPUs\n// the Adreno bug is only when gl_FrontFacing is inside a function\n// https://bugs.chromium.org/p/chromium/issues/detail?id=1154842\nvec3 getNormal(bool isFrontFacing){\n #ifdef RENDERER_HAS_NORMAL\n vec3 normal = normalize(v_normal);\n #elif defined(HAS_DERIVATIVES)\n vec3 pos_dx = dFdx(v_pos);\n vec3 pos_dy = dFdy(v_pos);\n vec3 normal = normalize( cross(pos_dx, pos_dy) );\n normal *= camera_ProjectionParams.x;\n #else\n vec3 normal = vec3(0, 0, 1);\n #endif\n\n normal *= float( isFrontFacing ) * 2.0 - 1.0;\n return normal;\n}\n\nvec3 getNormalByNormalTexture(mat3 tbn, sampler2D normalTexture, float normalIntensity, vec2 uv, bool isFrontFacing){\n vec3 normal = texture2D(normalTexture, uv).rgb;\n normal = normalize(tbn * ((2.0 * normal - 1.0) * vec3(normalIntensity, normalIntensity, 1.0)));\n normal *= float( isFrontFacing ) * 2.0 - 1.0;\n\n return normal;\n}\n\nmat3 getTBN(bool isFrontFacing){\n #if defined(RENDERER_HAS_NORMAL) && defined(RENDERER_HAS_TANGENT) && ( defined(MATERIAL_HAS_NORMALTEXTURE) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL_TEXTURE) || defined(MATERIAL_ENABLE_ANISOTROPY) )\n mat3 tbn = v_TBN;\n #else\n vec3 normal = getNormal(isFrontFacing);\n vec3 position = v_pos;\n vec2 uv = isFrontFacing? v_uv: -v_uv;\n\n #ifdef HAS_DERIVATIVES\n // ref: http://www.thetenthplanet.de/archives/1180\n // get edge vectors of the pixel triangle\n\t vec3 dp1 = dFdx(position);\n\t vec3 dp2 = dFdy(position);\n\t vec2 duv1 = dFdx(uv);\n\t vec2 duv2 = dFdy(uv);\n\n\t // solve the linear system\n\t vec3 dp2perp = cross(dp2, normal);\n\t vec3 dp1perp = cross(normal, dp1);\n\t vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n\t vec3 bitangent = dp2perp * duv1.y + dp1perp * duv2.y;\n\n\t // construct a scale-invariant frame \n float denom = max( dot(tangent, tangent), dot(bitangent, bitangent) );\n float invmax = (denom == 0.0) ? 0.0 : camera_ProjectionParams.x / sqrt( denom );\n\t mat3 tbn = mat3(tangent * invmax, bitangent * invmax, normal);\n #else\n mat3 tbn = mat3(vec3(0.0), vec3(0.0), normal);\n #endif\n #endif\n\t\n return tbn;\n}"; // eslint-disable-line
4932
-
4933
- var ShaderLib = _extends({
4934
- common: common,
4935
- common_vert: common_vert,
4936
- transform_declare: transform_declare,
4937
- camera_declare: camera_declare,
4938
- color_share: color_share,
4939
- normal_share: normal_share,
4940
- uv_share: uv_share,
4941
- worldpos_share: worldpos_share,
4942
- FogVertexDeclaration: FogVertexDeclaration,
4943
- FogFragmentDeclaration: FogFragmentDeclaration,
4944
- PositionClipSpaceDeclaration: PositionClipSpaceDeclaration,
4945
- begin_normal_vert: begin_normal_vert,
4946
- begin_position_vert: begin_position_vert,
4947
- position_vert: position_vert,
4948
- color_vert: color_vert,
4949
- normal_vert: normal_vert,
4950
- skinning_vert: skinning_vert,
4951
- blendShape_input: blendShape_input,
4952
- blendShape_vert: blendShape_vert,
4953
- uv_vert: uv_vert,
4954
- worldpos_vert: worldpos_vert,
4955
- FogVertex: FogVertex,
4956
- light_frag_define: light_frag_define,
4957
- mobile_material_frag: mobile_material_frag,
4958
- FogFragment: FogFragment,
4959
- PositionClipSpaceVertex: PositionClipSpaceVertex,
4960
- begin_mobile_frag: begin_mobile_frag,
4961
- begin_viewdir_frag: begin_viewdir_frag,
4962
- mobile_blinnphong_frag: mobile_blinnphong_frag,
4963
- noise_common: noise_common,
4964
- noise_simplex_3D_grad: noise_simplex_3D_grad
4965
- }, ShadowLib, PBRShaderLib, {
4966
- normal_get: normal_get
4967
- }, ParticleShaderLib);
4968
-
4969
- var ShaderFactory = /*#__PURE__*/ function() {
4775
+ /**
4776
+ * Shader registry and GLSL utilities. Holds the `#include` lookup table
4777
+ * the runtime preprocessor reads, and the GLSL ES 100 300 syntax
4778
+ * converter the WebGL2 path uses.
4779
+ */ var ShaderFactory = /*#__PURE__*/ function() {
4970
4780
  function ShaderFactory() {}
4971
- ShaderFactory.parseCustomMacros = function parseCustomMacros(macros) {
4972
- return macros.map(function(m) {
4973
- return "#define " + (m.value ? m.name + " " + m.value : m.name) + "\n";
4974
- }).join("");
4975
- };
4976
4781
  /**
4977
- * @internal
4978
- * Compile vertex and fragment source with standard macros, includes, and version header.
4979
- * @param engine - Engine instance
4980
- * @param macroCollection - Current macro collection
4981
- * @param vertexSource - Raw vertex shader source (may contain #include)
4982
- * @param fragmentSource - Raw fragment shader source
4983
- * @returns Compiled { vertexSource, fragmentSource } ready for ShaderProgram
4984
- */ ShaderFactory.compilePlatformSource = function compilePlatformSource(engine, macroCollection, vertexSource, fragmentSource) {
4985
- var isWebGL2 = engine._hardwareRenderer.isWebGL2;
4986
- var shaderMacroList = new Array();
4987
- ShaderMacro._getMacrosElements(macroCollection, shaderMacroList);
4988
- shaderMacroList.push(ShaderMacro.getByName(isWebGL2 ? "GRAPHICS_API_WEBGL2" : "GRAPHICS_API_WEBGL1"));
4989
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.shaderTextureLod)) {
4990
- shaderMacroList.push(ShaderMacro.getByName("HAS_TEX_LOD"));
4991
- }
4992
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.standardDerivatives)) {
4993
- shaderMacroList.push(ShaderMacro.getByName("HAS_DERIVATIVES"));
4994
- }
4995
- var noIncludeVertex = ShaderFactory.parseIncludes(vertexSource);
4996
- var noIncludeFrag = ShaderFactory.parseIncludes(fragmentSource);
4997
- var macroStr = ShaderFactory.parseCustomMacros(shaderMacroList);
4998
- noIncludeVertex = macroStr + noIncludeVertex;
4999
- noIncludeFrag = macroStr + noIncludeFrag;
5000
- if (isWebGL2) {
5001
- noIncludeVertex = ShaderFactory.convertTo300(noIncludeVertex);
5002
- noIncludeFrag = ShaderFactory.convertTo300(noIncludeFrag, true);
5003
- }
5004
- var versionStr = isWebGL2 ? "#version 300 es" : "#version 100";
5005
- var precisionStr = "\n#ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n#else\n precision mediump float;\n precision mediump int;\n#endif\n";
5006
- return {
5007
- vertexSource: versionStr + "\nprecision highp float;\n" + noIncludeVertex,
5008
- fragmentSource: versionStr + "\n" + (isWebGL2 ? "" : ShaderFactory._shaderExtension) + precisionStr + noIncludeFrag
5009
- };
5010
- };
5011
- ShaderFactory.registerInclude = function registerInclude(includeName, includeSource) {
5012
- if (ShaderLib[includeName]) {
4782
+ * Register a chunk source so `#include` resolves it.
4783
+ * @param includeName - The path key referenced in `#include "..."`.
4784
+ * @param includeSource - GLSL chunk source text.
4785
+ */ ShaderFactory.registerInclude = function registerInclude(includeName, includeSource) {
4786
+ if (ShaderFactory.includeMap[includeName]) {
5013
4787
  throw 'The "' + includeName + '" shader include already exist';
5014
4788
  }
5015
- ShaderLib[includeName] = includeSource;
5016
- };
5017
- ShaderFactory.unRegisterInclude = function unRegisterInclude(includeName) {
5018
- delete ShaderLib[includeName];
4789
+ ShaderFactory.includeMap[includeName] = includeSource;
5019
4790
  };
5020
4791
  /**
5021
- * @param regex The default regex is for engine's builtin glsl `#include` syntax,
5022
- * since `ShaderLab` use the same parsing function but different syntax for `#include` --- `/^[ \t]*#include +"([\w\d.]+)"/gm`
5023
- */ ShaderFactory.parseIncludes = function parseIncludes(src, regex) {
5024
- if (regex === void 0) regex = /^[ \t]*#include +<([\w\d.]+)>/gm;
5025
- function replace(match, slice) {
5026
- var _$replace = ShaderLib[slice];
5027
- if (_$replace === undefined) {
5028
- Logger.error('Shader slice "' + match.trim() + '" not founded.');
5029
- return "";
5030
- }
5031
- return ShaderFactory.parseIncludes(_$replace, regex);
5032
- }
5033
- return src.replace(regex, replace);
4792
+ * Remove a registered shader chunk.
4793
+ * @param includeName - The path key passed to `registerInclude`.
4794
+ */ ShaderFactory.unRegisterInclude = function unRegisterInclude(includeName) {
4795
+ delete ShaderFactory.includeMap[includeName];
5034
4796
  };
5035
4797
  /**
5036
4798
  * Convert lower GLSL version to GLSL 300 es.
5037
4799
  * @param shader - code
5038
4800
  * @param isFrag - Whether it is a fragment shader.
5039
- * */ ShaderFactory.convertTo300 = function convertTo300(shader, isFrag) {
4801
+ */ ShaderFactory.convertTo300 = function convertTo300(shader, isFrag) {
5040
4802
  shader = shader.replace(/\bvarying\b/g, isFrag ? "in" : "out");
5041
4803
  shader = shader.replace(/\btexture(2D|Cube)\b/g, "texture");
5042
4804
  shader = shader.replace(/\btexture2DProj\b/g, "textureProj");
@@ -5046,12 +4808,12 @@ var ShaderFactory = /*#__PURE__*/ function() {
5046
4808
  shader = shader.replace(/\btexture2DProjGradEXT\b/g, "textureProjGrad");
5047
4809
  if (isFrag) {
5048
4810
  shader = shader.replace(/\bgl_FragDepthEXT\b/g, "gl_FragDepth");
5049
- if (!ShaderFactory._has300Output(shader)) {
4811
+ if (!ShaderFactory._has300OutInFragReg.test(shader)) {
5050
4812
  var isMRT = /\bgl_FragData\[.+?\]/g.test(shader);
5051
4813
  if (isMRT) {
5052
4814
  shader = shader.replace(/\bgl_FragColor\b/g, "gl_FragData[0]");
5053
4815
  var result = shader.match(/\bgl_FragData\[.+?\]/g);
5054
- shader = this._replaceMRTShader(shader, result);
4816
+ shader = ShaderFactory._replaceMRTShader(shader, result);
5055
4817
  } else {
5056
4818
  shader = "out vec4 glFragColor;\n" + shader;
5057
4819
  shader = shader.replace(/\bgl_FragColor\b/g, "glFragColor");
@@ -5062,9 +4824,6 @@ var ShaderFactory = /*#__PURE__*/ function() {
5062
4824
  }
5063
4825
  return shader;
5064
4826
  };
5065
- ShaderFactory._has300Output = function _has300Output(fragmentShader) {
5066
- return ShaderFactory._has300OutInFragReg.test(fragmentShader);
5067
- };
5068
4827
  ShaderFactory._replaceMRTShader = function _replaceMRTShader(shader, result) {
5069
4828
  var declaration = "";
5070
4829
  var mrtIndexSet = new Set();
@@ -5082,7 +4841,8 @@ var ShaderFactory = /*#__PURE__*/ function() {
5082
4841
  };
5083
4842
  return ShaderFactory;
5084
4843
  }();
5085
- /** @internal */ ShaderFactory._shaderExtension = [
4844
+ ShaderFactory.includeMap = {};
4845
+ ShaderFactory.shaderExtension = [
5086
4846
  "GL_EXT_shader_texture_lod",
5087
4847
  "GL_OES_standard_derivatives",
5088
4848
  "GL_EXT_draw_buffers",
@@ -5090,8 +4850,8 @@ var ShaderFactory = /*#__PURE__*/ function() {
5090
4850
  ].map(function(e) {
5091
4851
  return "#extension " + e + " : enable\n";
5092
4852
  }).join("");
5093
- ShaderFactory._has300OutInFragReg = /\bout\s+(?:\w+\s+)?(?:vec4)\s+(?:\w+)\s*;/ // [layout(location = 0)] out [highp] vec4 [color];
5094
- ;
4853
+ // [layout(location = 0)] out [highp] vec4 [color];
4854
+ ShaderFactory._has300OutInFragReg = /\bout\s+(?:\w+\s+)?(?:vec4)\s+(?:\w+)\s*;/;
5095
4855
 
5096
4856
  /**
5097
4857
  * Shader tag key.
@@ -6209,147 +5969,6 @@ ShaderMacroProcessor._parsedFuncArgs = {
6209
5969
  end: 0
6210
5970
  };
6211
5971
 
6212
- var precisionStr = "\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n ";
6213
- /**
6214
- * Shader pass containing vertex and fragment source.
6215
- */ var ShaderPass = /*#__PURE__*/ function(ShaderPart) {
6216
- _inherits(ShaderPass, ShaderPart);
6217
- function ShaderPass(nameOrVertexSource, vertexSourceOrFragmentSourceOrInstructions, fragmentSourceOrTags, tagsOrPlatformTarget, tags) {
6218
- var _this;
6219
- _this = ShaderPart.call(this) || this, /** @internal */ _this._shaderPassId = 0, /** @internal */ _this._renderStateDataMap = {}, /** @internal */ _this._shaderProgramPools = [];
6220
- _this._shaderPassId = ShaderPass._shaderPassCounter++;
6221
- if (Array.isArray(vertexSourceOrFragmentSourceOrInstructions)) {
6222
- // Instructions overload: (name, vertexInst, fragInst, platformTarget, tags?)
6223
- _this._name = nameOrVertexSource;
6224
- _this._vertexShaderInstructions = vertexSourceOrFragmentSourceOrInstructions;
6225
- _this._fragmentShaderInstructions = fragmentSourceOrTags;
6226
- _this._platformTarget = tagsOrPlatformTarget;
6227
- tags = _extends({
6228
- pipelineStage: PipelineStage.Forward
6229
- }, tags);
6230
- } else if (typeof fragmentSourceOrTags === "string") {
6231
- // Named overload: (name, vertexSource, fragmentSource, tags?)
6232
- _this._name = nameOrVertexSource;
6233
- _this._vertexSource = vertexSourceOrFragmentSourceOrInstructions;
6234
- _this._fragmentSource = fragmentSourceOrTags;
6235
- tags = _extends({
6236
- pipelineStage: PipelineStage.Forward
6237
- }, tagsOrPlatformTarget);
6238
- } else {
6239
- // Unnamed overload: (vertexSource, fragmentSource, tags?)
6240
- _this._name = "Default";
6241
- _this._vertexSource = nameOrVertexSource;
6242
- _this._fragmentSource = vertexSourceOrFragmentSourceOrInstructions;
6243
- tags = _extends({
6244
- pipelineStage: PipelineStage.Forward
6245
- }, fragmentSourceOrTags);
6246
- }
6247
- for(var key in tags){
6248
- _this.setTag(key, tags[key]);
6249
- }
6250
- return _this;
6251
- }
6252
- var _proto = ShaderPass.prototype;
6253
- /**
6254
- * @internal
6255
- */ _proto._getShaderProgram = function _getShaderProgram(engine, macroCollection) {
6256
- var shaderProgramPool = engine._getShaderProgramPool(this._shaderPassId, this._shaderProgramPools);
6257
- var shaderProgram = shaderProgramPool.get(macroCollection);
6258
- if (shaderProgram) {
6259
- return shaderProgram;
6260
- }
6261
- shaderProgram = this._getCanonicalShaderProgram(engine, macroCollection);
6262
- shaderProgramPool.cache(shaderProgram);
6263
- return shaderProgram;
6264
- };
6265
- /**
6266
- * @internal
6267
- */ _proto._destroy = function _destroy() {
6268
- var shaderProgramPools = this._shaderProgramPools;
6269
- for(var i = 0, n = shaderProgramPools.length; i < n; i++){
6270
- var shaderProgramPool = shaderProgramPools[i];
6271
- shaderProgramPool._destroy();
6272
- delete shaderProgramPool.engine._shaderProgramPools[this._shaderPassId];
6273
- }
6274
- // Clear array storing multiple engine shader program pools
6275
- shaderProgramPools.length = 0;
6276
- };
6277
- _proto._getCanonicalShaderProgram = function _getCanonicalShaderProgram(engine, macroCollection) {
6278
- var _ref = this._platformTarget != undefined ? this._compileShaderLabSource(engine, macroCollection) : this._compilePlatformSource(engine, macroCollection), vertexSource = _ref.vertexSource, fragmentSource = _ref.fragmentSource;
6279
- return new ShaderProgram(engine, vertexSource, fragmentSource);
6280
- };
6281
- _proto._compilePlatformSource = function _compilePlatformSource(engine, macroCollection) {
6282
- return ShaderFactory.compilePlatformSource(engine, macroCollection, this._vertexSource, this._fragmentSource);
6283
- };
6284
- _proto._compileShaderLabSource = function _compileShaderLabSource(engine, macroCollection) {
6285
- var isWebGL2 = engine._hardwareRenderer.isWebGL2;
6286
- var shaderMacroList = ShaderPass._shaderMacroList;
6287
- shaderMacroList.length = 0;
6288
- ShaderMacro._getMacrosElements(macroCollection, shaderMacroList);
6289
- shaderMacroList.push(ShaderMacro.getByName(isWebGL2 ? "GRAPHICS_API_WEBGL2" : "GRAPHICS_API_WEBGL1"));
6290
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.shaderTextureLod)) {
6291
- shaderMacroList.push(ShaderMacro.getByName("HAS_TEX_LOD"));
6292
- }
6293
- if (engine._hardwareRenderer.canIUse(GLCapabilityType.standardDerivatives)) {
6294
- shaderMacroList.push(ShaderMacro.getByName("HAS_DERIVATIVES"));
6295
- }
6296
- var macroMap = ShaderPass._macroMap;
6297
- macroMap.clear();
6298
- for(var i = 0, n = shaderMacroList.length; i < n; i++){
6299
- var macro = shaderMacroList[i];
6300
- var _macro_value;
6301
- macroMap.set(macro.name, (_macro_value = macro.value) != null ? _macro_value : "");
6302
- }
6303
- var vertexSource = ShaderMacroProcessor.evaluate(this._vertexShaderInstructions, macroMap);
6304
- var fragmentSource = ShaderMacroProcessor.evaluate(this._fragmentShaderInstructions, macroMap);
6305
- if (isWebGL2 && this._platformTarget === ShaderLanguage.GLSLES100) {
6306
- vertexSource = ShaderFactory.convertTo300(vertexSource);
6307
- fragmentSource = ShaderFactory.convertTo300(fragmentSource, true);
6308
- }
6309
- var versionStr = isWebGL2 ? "#version 300 es" : "#version 100";
6310
- return {
6311
- vertexSource: " " + versionStr + "\n " + vertexSource + "\n ",
6312
- fragmentSource: " " + versionStr + "\n " + (isWebGL2 ? "" : ShaderFactory._shaderExtension) + "\n " + precisionStr + "\n " + fragmentSource + "\n "
6313
- };
6314
- };
6315
- return ShaderPass;
6316
- }(ShaderPart);
6317
- /** @internal */ ShaderPass._shaderPassCounter = 0;
6318
- /** @internal */ ShaderPass._shaderRootPath = "shaders://root/";
6319
- ShaderPass._shaderMacroList = [];
6320
- ShaderPass._macroMap = new Map();
6321
-
6322
- /**
6323
- * Sub shader.
6324
- */ var SubShader = /*#__PURE__*/ function(ShaderPart) {
6325
- _inherits(SubShader, ShaderPart);
6326
- function SubShader(name, passes, tags) {
6327
- var _this;
6328
- _this = ShaderPart.call(this) || this;
6329
- _this._name = name;
6330
- var passCount = passes.length;
6331
- if (passCount < 1) {
6332
- throw " count must large than 0.";
6333
- }
6334
- _this._passes = passes.slice();
6335
- for(var key in tags){
6336
- _this.setTag(key, tags[key]);
6337
- }
6338
- return _this;
6339
- }
6340
- _create_class(SubShader, [
6341
- {
6342
- key: "passes",
6343
- get: /**
6344
- * Sub shader passes.
6345
- */ function get() {
6346
- return this._passes;
6347
- }
6348
- }
6349
- ]);
6350
- return SubShader;
6351
- }(ShaderPart);
6352
-
6353
5972
  /**
6354
5973
  * The blend state of the render target.
6355
5974
  */ var RenderTargetBlendState = function RenderTargetBlendState() {
@@ -6375,55 +5994,59 @@ ShaderPass._macroMap = new Map();
6375
5994
  /**
6376
5995
  * @internal
6377
5996
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6378
- var blendState = this.targetBlendState;
6379
- var enable0Property = renderStateDataMap[RenderStateElementKey.BlendStateEnabled0];
6380
- if (enable0Property !== undefined) {
6381
- var enabled = shaderData.getFloat(enable0Property);
6382
- blendState.enabled = enabled !== undefined ? !!enabled : false;
6383
- }
6384
- var colorBlendOperation0Property = renderStateDataMap[RenderStateElementKey.BlendStateColorBlendOperation0];
6385
- if (colorBlendOperation0Property !== undefined) {
5997
+ var target = this.targetBlendState;
5998
+ var enabledProp = renderStateDataMap[RenderStateElementKey.BlendStateEnabled0];
5999
+ if (enabledProp !== undefined) {
6000
+ var enabled = shaderData.getFloat(enabledProp);
6001
+ target.enabled = enabled !== undefined ? !!enabled : false;
6002
+ }
6003
+ var colorBlendOperationProp = renderStateDataMap[RenderStateElementKey.BlendStateColorBlendOperation0];
6004
+ if (colorBlendOperationProp !== undefined) {
6386
6005
  var _shaderData_getFloat;
6387
- blendState.colorBlendOperation = (_shaderData_getFloat = shaderData.getFloat(colorBlendOperation0Property)) != null ? _shaderData_getFloat : BlendOperation.Add;
6006
+ target.colorBlendOperation = (_shaderData_getFloat = shaderData.getFloat(colorBlendOperationProp)) != null ? _shaderData_getFloat : BlendOperation.Add;
6388
6007
  }
6389
- var alphaBlendOperation0Property = renderStateDataMap[RenderStateElementKey.BlendStateAlphaBlendOperation0];
6390
- if (alphaBlendOperation0Property !== undefined) {
6008
+ var alphaBlendOperationProp = renderStateDataMap[RenderStateElementKey.BlendStateAlphaBlendOperation0];
6009
+ if (alphaBlendOperationProp !== undefined) {
6391
6010
  var _shaderData_getFloat1;
6392
- blendState.alphaBlendOperation = (_shaderData_getFloat1 = shaderData.getFloat(alphaBlendOperation0Property)) != null ? _shaderData_getFloat1 : BlendOperation.Add;
6011
+ target.alphaBlendOperation = (_shaderData_getFloat1 = shaderData.getFloat(alphaBlendOperationProp)) != null ? _shaderData_getFloat1 : BlendOperation.Add;
6393
6012
  }
6394
- var sourceColorBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateSourceColorBlendFactor0];
6395
- if (sourceColorBlendFactor0Property !== undefined) {
6013
+ var sourceColorBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateSourceColorBlendFactor0];
6014
+ if (sourceColorBlendFactorProp !== undefined) {
6396
6015
  var _shaderData_getFloat2;
6397
- blendState.sourceColorBlendFactor = (_shaderData_getFloat2 = shaderData.getFloat(sourceColorBlendFactor0Property)) != null ? _shaderData_getFloat2 : BlendFactor.One;
6016
+ target.sourceColorBlendFactor = (_shaderData_getFloat2 = shaderData.getFloat(sourceColorBlendFactorProp)) != null ? _shaderData_getFloat2 : BlendFactor.One;
6398
6017
  }
6399
- var sourceAlphaBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateSourceAlphaBlendFactor0];
6400
- if (sourceAlphaBlendFactor0Property !== undefined) {
6018
+ var sourceAlphaBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateSourceAlphaBlendFactor0];
6019
+ if (sourceAlphaBlendFactorProp !== undefined) {
6401
6020
  var _shaderData_getFloat3;
6402
- blendState.sourceAlphaBlendFactor = (_shaderData_getFloat3 = shaderData.getFloat(sourceAlphaBlendFactor0Property)) != null ? _shaderData_getFloat3 : BlendFactor.One;
6021
+ target.sourceAlphaBlendFactor = (_shaderData_getFloat3 = shaderData.getFloat(sourceAlphaBlendFactorProp)) != null ? _shaderData_getFloat3 : BlendFactor.One;
6403
6022
  }
6404
- var destinationColorBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateDestinationColorBlendFactor0];
6405
- if (destinationColorBlendFactor0Property !== undefined) {
6023
+ var destinationColorBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateDestinationColorBlendFactor0];
6024
+ if (destinationColorBlendFactorProp !== undefined) {
6406
6025
  var _shaderData_getFloat4;
6407
- blendState.destinationColorBlendFactor = (_shaderData_getFloat4 = shaderData.getFloat(destinationColorBlendFactor0Property)) != null ? _shaderData_getFloat4 : BlendFactor.Zero;
6026
+ target.destinationColorBlendFactor = (_shaderData_getFloat4 = shaderData.getFloat(destinationColorBlendFactorProp)) != null ? _shaderData_getFloat4 : BlendFactor.Zero;
6408
6027
  }
6409
- var destinationAlphaBlendFactor0Property = renderStateDataMap[RenderStateElementKey.BlendStateDestinationAlphaBlendFactor0];
6410
- if (destinationAlphaBlendFactor0Property !== undefined) {
6028
+ var destinationAlphaBlendFactorProp = renderStateDataMap[RenderStateElementKey.BlendStateDestinationAlphaBlendFactor0];
6029
+ if (destinationAlphaBlendFactorProp !== undefined) {
6411
6030
  var _shaderData_getFloat5;
6412
- blendState.destinationAlphaBlendFactor = (_shaderData_getFloat5 = shaderData.getFloat(destinationAlphaBlendFactor0Property)) != null ? _shaderData_getFloat5 : BlendFactor.Zero;
6031
+ target.destinationAlphaBlendFactor = (_shaderData_getFloat5 = shaderData.getFloat(destinationAlphaBlendFactorProp)) != null ? _shaderData_getFloat5 : BlendFactor.Zero;
6413
6032
  }
6414
- var colorWriteMask0Property = renderStateDataMap[RenderStateElementKey.BlendStateColorWriteMask0];
6415
- if (colorWriteMask0Property !== undefined) {
6033
+ var colorWriteMaskProp = renderStateDataMap[RenderStateElementKey.BlendStateColorWriteMask0];
6034
+ if (colorWriteMaskProp !== undefined) {
6416
6035
  var _shaderData_getFloat6;
6417
- blendState.colorWriteMask = (_shaderData_getFloat6 = shaderData.getFloat(colorWriteMask0Property)) != null ? _shaderData_getFloat6 : ColorWriteMask.All;
6036
+ target.colorWriteMask = (_shaderData_getFloat6 = shaderData.getFloat(colorWriteMaskProp)) != null ? _shaderData_getFloat6 : ColorWriteMask.All;
6418
6037
  }
6419
- var blendColorProperty = renderStateDataMap[RenderStateElementKey.BlendStateBlendColor];
6420
- if (blendColorProperty !== undefined) {
6421
- var blendColor = shaderData.getColor(blendColorProperty);
6422
- blendColor !== undefined && this.blendColor.copyFrom(blendColor);
6038
+ var blendColorProp = renderStateDataMap[RenderStateElementKey.BlendStateBlendColor];
6039
+ if (blendColorProp !== undefined) {
6040
+ var blendColor = shaderData.getColor(blendColorProp);
6041
+ if (blendColor) {
6042
+ this.blendColor.copyFrom(blendColor);
6043
+ } else {
6044
+ this.blendColor.set(0, 0, 0, 0);
6045
+ }
6423
6046
  }
6424
- var alphaToCoverageProperty = renderStateDataMap[RenderStateElementKey.BlendStateAlphaToCoverage];
6425
- if (alphaToCoverageProperty !== undefined) {
6426
- var alphaToCoverage = shaderData.getFloat(alphaToCoverageProperty);
6047
+ var alphaToCoverageProp = renderStateDataMap[RenderStateElementKey.BlendStateAlphaToCoverage];
6048
+ if (alphaToCoverageProp !== undefined) {
6049
+ var alphaToCoverage = shaderData.getFloat(alphaToCoverageProp);
6427
6050
  this.alphaToCoverage = alphaToCoverage !== undefined ? !!alphaToCoverage : false;
6428
6051
  }
6429
6052
  };
@@ -6560,20 +6183,20 @@ __decorate([
6560
6183
  /**
6561
6184
  * @internal
6562
6185
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6563
- var enableProperty = renderStateDataMap[RenderStateElementKey.DepthStateEnabled];
6564
- if (enableProperty !== undefined) {
6565
- var enabled = shaderData.getFloat(enableProperty);
6566
- this.enabled = enabled !== undefined ? !!enabled : false;
6567
- }
6568
- var writeEnabledProperty = renderStateDataMap[RenderStateElementKey.DepthStateWriteEnabled];
6569
- if (writeEnabledProperty !== undefined) {
6570
- var writeEnabled = shaderData.getFloat(writeEnabledProperty);
6571
- this.writeEnabled = writeEnabled !== undefined ? !!writeEnabled : false;
6572
- }
6573
- var compareFunctionProperty = renderStateDataMap[RenderStateElementKey.DepthStateCompareFunction];
6574
- if (compareFunctionProperty !== undefined) {
6186
+ var enabledProp = renderStateDataMap[RenderStateElementKey.DepthStateEnabled];
6187
+ if (enabledProp !== undefined) {
6188
+ var enabled = shaderData.getFloat(enabledProp);
6189
+ this.enabled = enabled !== undefined ? !!enabled : true;
6190
+ }
6191
+ var writeEnabledProp = renderStateDataMap[RenderStateElementKey.DepthStateWriteEnabled];
6192
+ if (writeEnabledProp !== undefined) {
6193
+ var writeEnabled = shaderData.getFloat(writeEnabledProp);
6194
+ this.writeEnabled = writeEnabled !== undefined ? !!writeEnabled : true;
6195
+ }
6196
+ var compareFunctionProp = renderStateDataMap[RenderStateElementKey.DepthStateCompareFunction];
6197
+ if (compareFunctionProp !== undefined) {
6575
6198
  var _shaderData_getFloat;
6576
- this.compareFunction = (_shaderData_getFloat = shaderData.getFloat(compareFunctionProperty)) != null ? _shaderData_getFloat : CompareFunction.Less;
6199
+ this.compareFunction = (_shaderData_getFloat = shaderData.getFloat(compareFunctionProp)) != null ? _shaderData_getFloat : CompareFunction.Less;
6577
6200
  }
6578
6201
  };
6579
6202
  /**
@@ -6648,20 +6271,20 @@ __decorate([
6648
6271
  /**
6649
6272
  * @internal
6650
6273
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6651
- var cullModeProperty = renderStateDataMap[RenderStateElementKey.RasterStateCullMode];
6652
- if (cullModeProperty !== undefined) {
6274
+ var cullModeProp = renderStateDataMap[RenderStateElementKey.RasterStateCullMode];
6275
+ if (cullModeProp !== undefined) {
6653
6276
  var _shaderData_getFloat;
6654
- this.cullMode = (_shaderData_getFloat = shaderData.getFloat(cullModeProperty)) != null ? _shaderData_getFloat : CullMode.Back;
6277
+ this.cullMode = (_shaderData_getFloat = shaderData.getFloat(cullModeProp)) != null ? _shaderData_getFloat : CullMode.Back;
6655
6278
  }
6656
- var depthBiasProperty = renderStateDataMap[RenderStateElementKey.RasterStateDepthBias];
6657
- if (depthBiasProperty !== undefined) {
6279
+ var depthBiasProp = renderStateDataMap[RenderStateElementKey.RasterStateDepthBias];
6280
+ if (depthBiasProp !== undefined) {
6658
6281
  var _shaderData_getFloat1;
6659
- this.depthBias = (_shaderData_getFloat1 = shaderData.getFloat(depthBiasProperty)) != null ? _shaderData_getFloat1 : 0;
6282
+ this.depthBias = (_shaderData_getFloat1 = shaderData.getFloat(depthBiasProp)) != null ? _shaderData_getFloat1 : 0;
6660
6283
  }
6661
- var slopeScaledDepthBiasProperty = renderStateDataMap[RenderStateElementKey.RasterStateSlopeScaledDepthBias];
6662
- if (slopeScaledDepthBiasProperty !== undefined) {
6284
+ var slopeScaledDepthBiasProp = renderStateDataMap[RenderStateElementKey.RasterStateSlopeScaledDepthBias];
6285
+ if (slopeScaledDepthBiasProp !== undefined) {
6663
6286
  var _shaderData_getFloat2;
6664
- this.slopeScaledDepthBias = (_shaderData_getFloat2 = shaderData.getFloat(slopeScaledDepthBiasProperty)) != null ? _shaderData_getFloat2 : 0;
6287
+ this.slopeScaledDepthBias = (_shaderData_getFloat2 = shaderData.getFloat(slopeScaledDepthBiasProp)) != null ? _shaderData_getFloat2 : 0;
6665
6288
  }
6666
6289
  };
6667
6290
  /**
@@ -6742,65 +6365,65 @@ __decorate([
6742
6365
  /**
6743
6366
  * @internal
6744
6367
  */ _proto._applyShaderDataValue = function _applyShaderDataValue(renderStateDataMap, shaderData) {
6745
- var enableProperty = renderStateDataMap[RenderStateElementKey.StencilStateEnabled];
6746
- if (enableProperty !== undefined) {
6747
- var enabled = shaderData.getFloat(enableProperty);
6368
+ var enabledProp = renderStateDataMap[RenderStateElementKey.StencilStateEnabled];
6369
+ if (enabledProp !== undefined) {
6370
+ var enabled = shaderData.getFloat(enabledProp);
6748
6371
  this.enabled = enabled !== undefined ? !!enabled : false;
6749
6372
  }
6750
- var referenceValueProperty = renderStateDataMap[RenderStateElementKey.StencilStateReferenceValue];
6751
- if (referenceValueProperty !== undefined) {
6373
+ var referenceValueProp = renderStateDataMap[RenderStateElementKey.StencilStateReferenceValue];
6374
+ if (referenceValueProp !== undefined) {
6752
6375
  var _shaderData_getFloat;
6753
- this.referenceValue = (_shaderData_getFloat = shaderData.getFloat(referenceValueProperty)) != null ? _shaderData_getFloat : 0;
6376
+ this.referenceValue = (_shaderData_getFloat = shaderData.getFloat(referenceValueProp)) != null ? _shaderData_getFloat : 0;
6754
6377
  }
6755
- var maskProperty = renderStateDataMap[RenderStateElementKey.StencilStateMask];
6756
- if (maskProperty !== undefined) {
6378
+ var maskProp = renderStateDataMap[RenderStateElementKey.StencilStateMask];
6379
+ if (maskProp !== undefined) {
6757
6380
  var _shaderData_getFloat1;
6758
- this.mask = (_shaderData_getFloat1 = shaderData.getFloat(maskProperty)) != null ? _shaderData_getFloat1 : 0xff;
6381
+ this.mask = (_shaderData_getFloat1 = shaderData.getFloat(maskProp)) != null ? _shaderData_getFloat1 : 0xff;
6759
6382
  }
6760
- var writeMaskProperty = renderStateDataMap[RenderStateElementKey.StencilStateWriteMask];
6761
- if (writeMaskProperty !== undefined) {
6383
+ var writeMaskProp = renderStateDataMap[RenderStateElementKey.StencilStateWriteMask];
6384
+ if (writeMaskProp !== undefined) {
6762
6385
  var _shaderData_getFloat2;
6763
- this.writeMask = (_shaderData_getFloat2 = shaderData.getFloat(writeMaskProperty)) != null ? _shaderData_getFloat2 : 0xff;
6386
+ this.writeMask = (_shaderData_getFloat2 = shaderData.getFloat(writeMaskProp)) != null ? _shaderData_getFloat2 : 0xff;
6764
6387
  }
6765
- var compareFunctionFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionFront];
6766
- if (compareFunctionFrontProperty !== undefined) {
6388
+ var compareFunctionFrontProp = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionFront];
6389
+ if (compareFunctionFrontProp !== undefined) {
6767
6390
  var _shaderData_getFloat3;
6768
- this.compareFunctionFront = (_shaderData_getFloat3 = shaderData.getFloat(compareFunctionFrontProperty)) != null ? _shaderData_getFloat3 : CompareFunction.Always;
6391
+ this.compareFunctionFront = (_shaderData_getFloat3 = shaderData.getFloat(compareFunctionFrontProp)) != null ? _shaderData_getFloat3 : CompareFunction.Always;
6769
6392
  }
6770
- var compareFunctionBackProperty = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionBack];
6771
- if (compareFunctionBackProperty !== undefined) {
6393
+ var compareFunctionBackProp = renderStateDataMap[RenderStateElementKey.StencilStateCompareFunctionBack];
6394
+ if (compareFunctionBackProp !== undefined) {
6772
6395
  var _shaderData_getFloat4;
6773
- this.compareFunctionBack = (_shaderData_getFloat4 = shaderData.getFloat(compareFunctionBackProperty)) != null ? _shaderData_getFloat4 : CompareFunction.Always;
6396
+ this.compareFunctionBack = (_shaderData_getFloat4 = shaderData.getFloat(compareFunctionBackProp)) != null ? _shaderData_getFloat4 : CompareFunction.Always;
6774
6397
  }
6775
- var passOperationFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationFront];
6776
- if (passOperationFrontProperty !== undefined) {
6398
+ var passOperationFrontProp = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationFront];
6399
+ if (passOperationFrontProp !== undefined) {
6777
6400
  var _shaderData_getFloat5;
6778
- this.passOperationFront = (_shaderData_getFloat5 = shaderData.getFloat(passOperationFrontProperty)) != null ? _shaderData_getFloat5 : StencilOperation.Keep;
6401
+ this.passOperationFront = (_shaderData_getFloat5 = shaderData.getFloat(passOperationFrontProp)) != null ? _shaderData_getFloat5 : StencilOperation.Keep;
6779
6402
  }
6780
- var passOperationBackProperty = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationBack];
6781
- if (passOperationBackProperty !== undefined) {
6403
+ var passOperationBackProp = renderStateDataMap[RenderStateElementKey.StencilStatePassOperationBack];
6404
+ if (passOperationBackProp !== undefined) {
6782
6405
  var _shaderData_getFloat6;
6783
- this.passOperationBack = (_shaderData_getFloat6 = shaderData.getFloat(passOperationBackProperty)) != null ? _shaderData_getFloat6 : StencilOperation.Keep;
6406
+ this.passOperationBack = (_shaderData_getFloat6 = shaderData.getFloat(passOperationBackProp)) != null ? _shaderData_getFloat6 : StencilOperation.Keep;
6784
6407
  }
6785
- var failOperationFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationFront];
6786
- if (failOperationFrontProperty !== undefined) {
6408
+ var failOperationFrontProp = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationFront];
6409
+ if (failOperationFrontProp !== undefined) {
6787
6410
  var _shaderData_getFloat7;
6788
- this.failOperationFront = (_shaderData_getFloat7 = shaderData.getFloat(failOperationFrontProperty)) != null ? _shaderData_getFloat7 : StencilOperation.Keep;
6411
+ this.failOperationFront = (_shaderData_getFloat7 = shaderData.getFloat(failOperationFrontProp)) != null ? _shaderData_getFloat7 : StencilOperation.Keep;
6789
6412
  }
6790
- var failOperationBackProperty = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationBack];
6791
- if (failOperationBackProperty !== undefined) {
6413
+ var failOperationBackProp = renderStateDataMap[RenderStateElementKey.StencilStateFailOperationBack];
6414
+ if (failOperationBackProp !== undefined) {
6792
6415
  var _shaderData_getFloat8;
6793
- this.failOperationBack = (_shaderData_getFloat8 = shaderData.getFloat(failOperationBackProperty)) != null ? _shaderData_getFloat8 : StencilOperation.Keep;
6416
+ this.failOperationBack = (_shaderData_getFloat8 = shaderData.getFloat(failOperationBackProp)) != null ? _shaderData_getFloat8 : StencilOperation.Keep;
6794
6417
  }
6795
- var zFailOperationFrontProperty = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationFront];
6796
- if (zFailOperationFrontProperty !== undefined) {
6418
+ var zFailOperationFrontProp = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationFront];
6419
+ if (zFailOperationFrontProp !== undefined) {
6797
6420
  var _shaderData_getFloat9;
6798
- this.zFailOperationFront = (_shaderData_getFloat9 = shaderData.getFloat(zFailOperationFrontProperty)) != null ? _shaderData_getFloat9 : StencilOperation.Keep;
6421
+ this.zFailOperationFront = (_shaderData_getFloat9 = shaderData.getFloat(zFailOperationFrontProp)) != null ? _shaderData_getFloat9 : StencilOperation.Keep;
6799
6422
  }
6800
- var zFailOperationBackProperty = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationBack];
6801
- if (zFailOperationBackProperty !== undefined) {
6423
+ var zFailOperationBackProp = renderStateDataMap[RenderStateElementKey.StencilStateZFailOperationBack];
6424
+ if (zFailOperationBackProp !== undefined) {
6802
6425
  var _shaderData_getFloat10;
6803
- this.zFailOperationBack = (_shaderData_getFloat10 = shaderData.getFloat(zFailOperationBackProperty)) != null ? _shaderData_getFloat10 : StencilOperation.Keep;
6426
+ this.zFailOperationBack = (_shaderData_getFloat10 = shaderData.getFloat(zFailOperationBackProp)) != null ? _shaderData_getFloat10 : StencilOperation.Keep;
6804
6427
  }
6805
6428
  };
6806
6429
  /**
@@ -6937,8 +6560,10 @@ __decorate([
6937
6560
  /**
6938
6561
  * @internal
6939
6562
  */ _proto._applyStates = function _applyStates(engine, frontFaceInvert, renderStateDataMap, shaderData, customRenderStates) {
6940
- // @todo: Should merge when we can delete material render state
6941
- renderStateDataMap && this._applyStatesByShaderData(renderStateDataMap, shaderData);
6563
+ this.blendState._applyShaderDataValue(renderStateDataMap, shaderData);
6564
+ this.depthState._applyShaderDataValue(renderStateDataMap, shaderData);
6565
+ this.stencilState._applyShaderDataValue(renderStateDataMap, shaderData);
6566
+ this.rasterState._applyShaderDataValue(renderStateDataMap, shaderData);
6942
6567
  var hardwareRenderer = engine._hardwareRenderer;
6943
6568
  var lastRenderState = engine._lastRenderState;
6944
6569
  var context = engine._renderContext;
@@ -6949,21 +6574,13 @@ __decorate([
6949
6574
  };
6950
6575
  /**
6951
6576
  * @internal
6952
- * @todo Should merge when we can delete material render state
6953
6577
  */ _proto._getRenderQueueByShaderData = function _getRenderQueueByShaderData(renderStateDataMap, shaderData) {
6954
- var renderQueueType = renderStateDataMap[RenderStateElementKey.RenderQueueType];
6955
- if (renderQueueType === undefined) {
6956
- return this.renderQueueType;
6957
- } else {
6958
- var _shaderData_getFloat;
6959
- return (_shaderData_getFloat = shaderData.getFloat(renderQueueType)) != null ? _shaderData_getFloat : RenderQueueType.Opaque;
6578
+ var renderQueueTypeProp = renderStateDataMap[RenderStateElementKey.RenderQueueType];
6579
+ if (renderQueueTypeProp !== undefined) {
6580
+ var renderQueueType = shaderData.getFloat(renderQueueTypeProp);
6581
+ if (renderQueueType !== undefined) return renderQueueType;
6960
6582
  }
6961
- };
6962
- _proto._applyStatesByShaderData = function _applyStatesByShaderData(renderStateDataMap, shaderData) {
6963
- this.blendState._applyShaderDataValue(renderStateDataMap, shaderData);
6964
- this.depthState._applyShaderDataValue(renderStateDataMap, shaderData);
6965
- this.stencilState._applyShaderDataValue(renderStateDataMap, shaderData);
6966
- this.rasterState._applyShaderDataValue(renderStateDataMap, shaderData);
6583
+ return this.renderQueueType;
6967
6584
  };
6968
6585
  return RenderState;
6969
6586
  }();
@@ -6980,6 +6597,125 @@ __decorate([
6980
6597
  deepClone
6981
6598
  ], RenderState.prototype, "rasterState", void 0);
6982
6599
 
6600
+ var precisionStr = "\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n precision highp int;\n #else\n precision mediump float;\n precision mediump int;\n #endif\n ";
6601
+ /**
6602
+ * Shader pass containing vertex and fragment source.
6603
+ */ var ShaderPass = /*#__PURE__*/ function(ShaderPart) {
6604
+ _inherits(ShaderPass, ShaderPart);
6605
+ function ShaderPass(name, vertexShaderInstructions, fragmentShaderInstructions, platformTarget, tags) {
6606
+ var _this;
6607
+ _this = ShaderPart.call(this) || this, /** @internal */ _this._shaderPassId = 0, /** @internal Pass-level render state — always present, populated from ShaderLab declarations. */ _this._renderState = new RenderState(), /** @internal */ _this._renderStateDataMap = {}, /** @internal */ _this._shaderProgramPools = [];
6608
+ _this._shaderPassId = ShaderPass._shaderPassCounter++;
6609
+ _this._name = name;
6610
+ _this._vertexShaderInstructions = vertexShaderInstructions;
6611
+ _this._fragmentShaderInstructions = fragmentShaderInstructions;
6612
+ _this._platformTarget = platformTarget;
6613
+ var mergedTags = _extends({
6614
+ pipelineStage: PipelineStage.Forward
6615
+ }, tags);
6616
+ for(var key in mergedTags){
6617
+ _this.setTag(key, mergedTags[key]);
6618
+ }
6619
+ return _this;
6620
+ }
6621
+ var _proto = ShaderPass.prototype;
6622
+ /**
6623
+ * @internal
6624
+ */ _proto._getShaderProgram = function _getShaderProgram(engine, macroCollection) {
6625
+ var shaderProgramPool = engine._getShaderProgramPool(this._shaderPassId, this._shaderProgramPools);
6626
+ var shaderProgram = shaderProgramPool.get(macroCollection);
6627
+ if (shaderProgram) {
6628
+ return shaderProgram;
6629
+ }
6630
+ shaderProgram = this._getCanonicalShaderProgram(engine, macroCollection);
6631
+ shaderProgramPool.cache(shaderProgram);
6632
+ return shaderProgram;
6633
+ };
6634
+ /**
6635
+ * @internal
6636
+ */ _proto._destroy = function _destroy() {
6637
+ var shaderProgramPools = this._shaderProgramPools;
6638
+ for(var i = 0, n = shaderProgramPools.length; i < n; i++){
6639
+ var shaderProgramPool = shaderProgramPools[i];
6640
+ shaderProgramPool._destroy();
6641
+ delete shaderProgramPool.engine._shaderProgramPools[this._shaderPassId];
6642
+ }
6643
+ // Clear array storing multiple engine shader program pools
6644
+ shaderProgramPools.length = 0;
6645
+ };
6646
+ _proto._getCanonicalShaderProgram = function _getCanonicalShaderProgram(engine, macroCollection) {
6647
+ var _this__compileShaderSource = this._compileShaderSource(engine, macroCollection), vertexSource = _this__compileShaderSource.vertexSource, fragmentSource = _this__compileShaderSource.fragmentSource;
6648
+ return new ShaderProgram(engine, vertexSource, fragmentSource, this._feedbackVaryings);
6649
+ };
6650
+ _proto._compileShaderSource = function _compileShaderSource(engine, macroCollection) {
6651
+ var isWebGL2 = engine._hardwareRenderer.isWebGL2;
6652
+ var shaderMacroList = ShaderPass._shaderMacroList;
6653
+ shaderMacroList.length = 0;
6654
+ ShaderMacro._getMacrosElements(macroCollection, shaderMacroList);
6655
+ shaderMacroList.push(ShaderMacro.getByName(isWebGL2 ? "GRAPHICS_API_WEBGL2" : "GRAPHICS_API_WEBGL1"));
6656
+ if (engine._hardwareRenderer.canIUse(GLCapabilityType.shaderTextureLod)) {
6657
+ shaderMacroList.push(ShaderMacro.getByName("HAS_TEX_LOD"));
6658
+ }
6659
+ if (engine._hardwareRenderer.canIUse(GLCapabilityType.standardDerivatives)) {
6660
+ shaderMacroList.push(ShaderMacro.getByName("HAS_DERIVATIVES"));
6661
+ }
6662
+ var macroMap = ShaderPass._macroMap;
6663
+ macroMap.clear();
6664
+ for(var i = 0, n = shaderMacroList.length; i < n; i++){
6665
+ var macro = shaderMacroList[i];
6666
+ var _macro_value;
6667
+ macroMap.set(macro.name, (_macro_value = macro.value) != null ? _macro_value : "");
6668
+ }
6669
+ var vertexSource = ShaderMacroProcessor.evaluate(this._vertexShaderInstructions, macroMap);
6670
+ var fragmentSource = ShaderMacroProcessor.evaluate(this._fragmentShaderInstructions, macroMap);
6671
+ if (isWebGL2 && this._platformTarget === ShaderLanguage.GLSLES100) {
6672
+ vertexSource = ShaderFactory.convertTo300(vertexSource);
6673
+ fragmentSource = ShaderFactory.convertTo300(fragmentSource, true);
6674
+ }
6675
+ var versionStr = isWebGL2 ? "#version 300 es" : "#version 100";
6676
+ return {
6677
+ vertexSource: " " + versionStr + "\n " + vertexSource + "\n ",
6678
+ fragmentSource: " " + versionStr + "\n " + (isWebGL2 ? "" : ShaderFactory.shaderExtension) + "\n " + precisionStr + "\n " + fragmentSource + "\n "
6679
+ };
6680
+ };
6681
+ return ShaderPass;
6682
+ }(ShaderPart);
6683
+ /** @internal */ ShaderPass._shaderPassCounter = 0;
6684
+ /** @internal */ ShaderPass._shaderRootPath = "shaders://root/";
6685
+ ShaderPass._shaderMacroList = [];
6686
+ ShaderPass._macroMap = new Map();
6687
+
6688
+ /**
6689
+ * Sub shader.
6690
+ */ var SubShader = /*#__PURE__*/ function(ShaderPart) {
6691
+ _inherits(SubShader, ShaderPart);
6692
+ function SubShader(name, passes, tags) {
6693
+ var _this;
6694
+ _this = ShaderPart.call(this) || this;
6695
+ _this._name = name;
6696
+ var passCount = passes.length;
6697
+ if (passCount < 1) {
6698
+ throw " count must large than 0.";
6699
+ }
6700
+ _this._passes = passes.slice();
6701
+ for(var key in tags){
6702
+ _this.setTag(key, tags[key]);
6703
+ }
6704
+ return _this;
6705
+ }
6706
+ _create_class(SubShader, [
6707
+ {
6708
+ key: "passes",
6709
+ get: /**
6710
+ * Sub shader passes.
6711
+ */ function get() {
6712
+ return this._passes;
6713
+ }
6714
+ }
6715
+ ]);
6716
+ return SubShader;
6717
+ }(ShaderPart);
6718
+
6983
6719
  /**
6984
6720
  * Shader for rendering.
6985
6721
  */ var Shader = /*#__PURE__*/ function() {
@@ -7047,32 +6783,33 @@ __decorate([
7047
6783
  */ _proto._addReferCount = function _addReferCount(value) {
7048
6784
  this._refCount += value;
7049
6785
  };
7050
- Shader.create = function create(nameOrShaderSource, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, fragmentSourceOrPath) {
6786
+ Shader.create = function create(nameOrShaderSource, shaderPassesOrSubShadersOrPlatformTarget, path) {
7051
6787
  var shader;
7052
6788
  var shaderMap = Shader._shaderMap;
7053
- if (vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget == undefined) {
7054
- vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget = ShaderLanguage.GLSLES100;
6789
+ if (shaderPassesOrSubShadersOrPlatformTarget == undefined) {
6790
+ shaderPassesOrSubShadersOrPlatformTarget = ShaderLanguage.GLSLES100;
7055
6791
  }
7056
- if (typeof vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget === "number") {
7057
- var shaderLab = Shader._shaderLab;
7058
- if (!shaderLab) {
7059
- throw "ShaderLab has not been set up yet.";
6792
+ if (typeof shaderPassesOrSubShadersOrPlatformTarget === "number") {
6793
+ var shaderCompiler = Shader._shaderCompiler;
6794
+ if (!shaderCompiler) {
6795
+ throw "ShaderCompiler has not been set up yet.";
7060
6796
  }
7061
- var shaderSource = shaderLab._parseShaderSource(nameOrShaderSource);
6797
+ var shaderSource = shaderCompiler._parseShaderSource(nameOrShaderSource);
7062
6798
  if (shaderMap[shaderSource.name]) {
7063
6799
  console.error('Shader named "' + shaderSource.name + '" already exists.');
7064
6800
  return;
7065
6801
  }
6802
+ var basePathForIncludeKey = new URL(path != null ? path : "", ShaderPass._shaderRootPath).href;
7066
6803
  var subShaderList = shaderSource.subShaders.map(function(subShaderSource) {
7067
6804
  var passList = subShaderSource.passes.map(function(passSource) {
7068
6805
  if (passSource.isUsePass) {
7069
6806
  return Shader._resolveUsePass(passSource.name);
7070
6807
  }
7071
- var shaderPassSource = Shader._shaderLab._parseShaderPass(passSource.contents, passSource.vertexEntry, passSource.fragmentEntry, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, new URL(fragmentSourceOrPath != null ? fragmentSourceOrPath : "", ShaderPass._shaderRootPath).href);
6808
+ var shaderPassSource = Shader._shaderCompiler._parseShaderPass(passSource.contents, passSource.vertexEntry, passSource.fragmentEntry, shaderPassesOrSubShadersOrPlatformTarget, basePathForIncludeKey);
7072
6809
  if (!shaderPassSource) {
7073
6810
  throw 'Shader pass "' + shaderSource.name + "." + subShaderSource.name + "." + passSource.name + '" parse failed, please check the shader source code.';
7074
6811
  }
7075
- var shaderPass = new ShaderPass(passSource.name, shaderPassSource.vertexShaderInstructions, shaderPassSource.fragmentShaderInstructions, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, passSource.tags);
6812
+ var shaderPass = new ShaderPass(passSource.name, shaderPassSource.vertexShaderInstructions, shaderPassSource.fragmentShaderInstructions, shaderPassesOrSubShadersOrPlatformTarget, passSource.tags);
7076
6813
  Shader._applyRenderStates(shaderPass, passSource.renderStates.constantMap, passSource.renderStates.variableMap, false);
7077
6814
  return shaderPass;
7078
6815
  });
@@ -7086,25 +6823,16 @@ __decorate([
7086
6823
  console.error('Shader named "' + nameOrShaderSource + '" already exists.');
7087
6824
  return;
7088
6825
  }
7089
- if (typeof vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget === "string") {
7090
- var shaderPass = new ShaderPass(vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget, fragmentSourceOrPath);
7091
- shader = new Shader(nameOrShaderSource, [
7092
- new SubShader("Default", [
7093
- shaderPass
7094
- ])
7095
- ]);
7096
- } else {
7097
- if (vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget.length > 0) {
7098
- if (vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget[0].constructor === ShaderPass) {
7099
- shader = new Shader(nameOrShaderSource, [
7100
- new SubShader("Default", vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget)
7101
- ]);
7102
- } else {
7103
- shader = new Shader(nameOrShaderSource, vertexSourceOrShaderPassesOrSubShadersOrPlatformTarget.slice());
7104
- }
6826
+ if (shaderPassesOrSubShadersOrPlatformTarget.length > 0) {
6827
+ if (shaderPassesOrSubShadersOrPlatformTarget[0].constructor === ShaderPass) {
6828
+ shader = new Shader(nameOrShaderSource, [
6829
+ new SubShader("Default", shaderPassesOrSubShadersOrPlatformTarget)
6830
+ ]);
7105
6831
  } else {
7106
- throw "SubShader or ShaderPass count must large than 0.";
6832
+ shader = new Shader(nameOrShaderSource, shaderPassesOrSubShadersOrPlatformTarget.slice());
7107
6833
  }
6834
+ } else {
6835
+ throw "SubShader or ShaderPass count must large than 0.";
7108
6836
  }
7109
6837
  }
7110
6838
  shaderMap[nameOrShaderSource] = shader;
@@ -7162,32 +6890,48 @@ __decorate([
7162
6890
  }
7163
6891
  };
7164
6892
  Shader._resolveUsePass = function _resolveUsePass(passName) {
7165
- var _Shader_find_subShaders_find, _Shader_find;
7166
- var _passName_split = passName.split("/"), shaderName = _passName_split[0], subShaderName = _passName_split[1], passNamePart = _passName_split[2];
7167
- return (_Shader_find = Shader.find(shaderName)) == null ? void 0 : (_Shader_find_subShaders_find = _Shader_find.subShaders.find(function(subShader) {
7168
- return subShader.name === subShaderName;
7169
- })) == null ? void 0 : _Shader_find_subShaders_find.passes.find(function(pass) {
7170
- return pass.name === passNamePart;
6893
+ var lastSlash = passName.lastIndexOf("/");
6894
+ var secondLastSlash = passName.lastIndexOf("/", lastSlash - 1);
6895
+ if (secondLastSlash <= 0) {
6896
+ throw new Error('UsePass "' + passName + '" must be formatted as "shaderName/subShaderName/passName".');
6897
+ }
6898
+ var shaderName = passName.substring(0, secondLastSlash);
6899
+ var subShaderName = passName.substring(secondLastSlash + 1, lastSlash);
6900
+ var passNamePart = passName.substring(lastSlash + 1);
6901
+ var shader = Shader.find(shaderName);
6902
+ if (!shader) {
6903
+ throw new Error('UsePass "' + passName + '": shader "' + shaderName + '" not found.');
6904
+ }
6905
+ var subShader = shader.subShaders.find(function(s) {
6906
+ return s.name === subShaderName;
6907
+ });
6908
+ if (!subShader) {
6909
+ throw new Error('UsePass "' + passName + '": subShader "' + subShaderName + '" not found in shader "' + shaderName + '".');
6910
+ }
6911
+ var pass = subShader.passes.find(function(p) {
6912
+ return p.name === passNamePart;
7171
6913
  });
6914
+ if (!pass) {
6915
+ throw new Error('UsePass "' + passName + '": pass "' + passNamePart + '" not found in subShader "' + subShaderName + '".');
6916
+ }
6917
+ return pass;
7172
6918
  };
7173
6919
  Shader._applyRenderStates = function _applyRenderStates(shaderPass, constantMap, variableMap, deserializeColor) {
7174
- if (Object.keys(constantMap).length > 0 || Object.keys(variableMap).length > 0) {
7175
- var renderState = new RenderState();
7176
- for(var k in constantMap){
7177
- var value = constantMap[k];
7178
- if (deserializeColor && Array.isArray(value)) {
7179
- Shader._applyConstRenderStates(renderState, +k, new engineMath.Color(value[0], value[1], value[2], value[3]));
7180
- } else {
7181
- Shader._applyConstRenderStates(renderState, +k, value);
7182
- }
7183
- }
7184
- shaderPass._renderState = renderState;
7185
- var renderStateDataMap = {};
7186
- for(var k1 in variableMap){
7187
- renderStateDataMap[k1] = ShaderProperty.getByName(variableMap[k1]);
6920
+ var renderState = new RenderState();
6921
+ for(var k in constantMap){
6922
+ var value = constantMap[k];
6923
+ if (deserializeColor && Array.isArray(value)) {
6924
+ Shader._applyConstRenderStates(renderState, +k, new engineMath.Color(value[0], value[1], value[2], value[3]));
6925
+ } else {
6926
+ Shader._applyConstRenderStates(renderState, +k, value);
7188
6927
  }
7189
- shaderPass._renderStateDataMap = renderStateDataMap;
7190
6928
  }
6929
+ shaderPass._renderState = renderState;
6930
+ var renderStateDataMap = {};
6931
+ for(var k1 in variableMap){
6932
+ renderStateDataMap[k1] = ShaderProperty.getByName(variableMap[k1]);
6933
+ }
6934
+ shaderPass._renderStateDataMap = renderStateDataMap;
7191
6935
  };
7192
6936
  Shader._applyConstRenderStates = function _applyConstRenderStates(renderState, key, value) {
7193
6937
  switch(key){
@@ -7667,7 +7411,7 @@ RenderContext._flipYViewProjectionMatrix = new engineMath.Matrix();
7667
7411
  var sceneData = scene.shaderData;
7668
7412
  var viewProjMatrix = Sky._viewProjMatrix, projectionMatrix = Sky._projectionMatrix;
7669
7413
  var rhi = engine._hardwareRenderer;
7670
- var materialShaderData = material.shaderData, shader = material.shader, renderState = material.renderState;
7414
+ var materialShaderData = material.shaderData, shader = material.shader;
7671
7415
  // no-scale view matrix
7672
7416
  viewProjMatrix.copyFrom(viewMatrix);
7673
7417
  var e = viewProjMatrix.elements;
@@ -7694,7 +7438,7 @@ RenderContext._flipYViewProjectionMatrix = new engineMath.Matrix();
7694
7438
  program.uploadAll(program.cameraUniformBlock, cameraShaderData);
7695
7439
  program.uploadAll(program.materialUniformBlock, materialShaderData);
7696
7440
  program.uploadUnGroupTextures();
7697
- renderState._applyStates(engine, false, pass._renderStateDataMap, materialShaderData);
7441
+ pass._renderState._applyStates(engine, false, pass._renderStateDataMap, materialShaderData);
7698
7442
  rhi.drawPrimitive(mesh._primitive, mesh.subMesh, program);
7699
7443
  cameraShaderData.setMatrix(RenderContext.vpMatrixProperty, originViewProjMatrix);
7700
7444
  };
@@ -7819,8 +7563,7 @@ Sky._projectionMatrix = new engineMath.Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, Sky.
7819
7563
  this._mesh._addReferCount(1);
7820
7564
  };
7821
7565
  _proto._initMaterial = function _initMaterial(engine) {
7822
- var material = this._material = new Material(engine, Shader.find("background-texture"));
7823
- material.renderState.depthState.compareFunction = CompareFunction.LessEqual;
7566
+ var material = this._material = new Material(engine, Shader.find("Sky/BackgroundTexture"));
7824
7567
  material._addReferCount(1);
7825
7568
  };
7826
7569
  _proto._createPlane = function _createPlane(engine) {
@@ -10024,8 +9767,7 @@ exports.Camera = __decorate([
10024
9767
  _inherits(Material, ReferResource);
10025
9768
  function Material(engine, shader) {
10026
9769
  var _this;
10027
- _this = ReferResource.call(this, engine) || this, /** @internal */ _this._renderStates = [] // todo: later will as a part of shaderData when shader effect frame is OK, that is more powerful and flexible.
10028
- , _this._shaderData = new ShaderData(ShaderDataGroup.Material);
9770
+ _this = ReferResource.call(this, engine) || this, _this._shaderData = new ShaderData(ShaderDataGroup.Material);
10029
9771
  _this.shader = shader;
10030
9772
  _this.name = shader.name;
10031
9773
  return _this;
@@ -10044,7 +9786,6 @@ exports.Camera = __decorate([
10044
9786
  */ _proto.cloneTo = function cloneTo(target) {
10045
9787
  target.shader = this.shader;
10046
9788
  this.shaderData.cloneTo(target.shaderData);
10047
- CloneManager.deepCloneObject(this.renderStates, target.renderStates, new Map());
10048
9789
  };
10049
9790
  _proto._addReferCount = function _addReferCount(value) {
10050
9791
  if (this._destroyed) return;
@@ -10062,8 +9803,6 @@ exports.Camera = __decorate([
10062
9803
  ReferResource.prototype._onDestroy.call(this);
10063
9804
  this._shader = null;
10064
9805
  this._shaderData = null;
10065
- this._renderStates.length = 0;
10066
- this._renderStates = null;
10067
9806
  };
10068
9807
  _create_class(Material, [
10069
9808
  {
@@ -10089,36 +9828,6 @@ exports.Camera = __decorate([
10089
9828
  value._addReferCount(refCount);
10090
9829
  }
10091
9830
  this._shader = value;
10092
- var renderStates = this._renderStates;
10093
- var lastStatesCount = renderStates.length;
10094
- var maxPassCount = 0;
10095
- var subShaders = value.subShaders;
10096
- for(var i = 0; i < subShaders.length; i++){
10097
- maxPassCount = Math.max(subShaders[i].passes.length, maxPassCount);
10098
- }
10099
- if (lastStatesCount < maxPassCount) {
10100
- for(var i1 = lastStatesCount; i1 < maxPassCount; i1++){
10101
- renderStates.push(new RenderState());
10102
- }
10103
- } else {
10104
- renderStates.length = maxPassCount;
10105
- }
10106
- }
10107
- },
10108
- {
10109
- key: "renderState",
10110
- get: /**
10111
- * First Render state.
10112
- */ function get() {
10113
- return this._renderStates[0];
10114
- }
10115
- },
10116
- {
10117
- key: "renderStates",
10118
- get: /**
10119
- * Render states.
10120
- */ function get() {
10121
- return this._renderStates;
10122
9831
  }
10123
9832
  }
10124
9833
  ]);
@@ -10134,77 +9843,63 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10134
9843
  shaderData.setFloat(BaseMaterial._alphaCutoffProp, 0);
10135
9844
  shaderData.setFloat(BaseMaterial._shadowCasterRenderQueueProp, RenderQueueType.Opaque);
10136
9845
  shaderData.setFloat(BaseMaterial._depthOnlyRenderQueueProp, RenderQueueType.Opaque);
9846
+ _this.setIsTransparent(false);
9847
+ _this.setRenderFace(RenderFace.Front);
9848
+ _this.setBlendMode(BlendMode.Normal);
10137
9849
  return _this;
10138
9850
  }
10139
9851
  var _proto = BaseMaterial.prototype;
10140
9852
  /**
10141
9853
  * Set if is transparent of the shader pass render state.
10142
- * @param passIndex - Shader pass index
10143
9854
  * @param isTransparent - If is transparent
10144
- */ _proto.setIsTransparent = function setIsTransparent(passIndex, isTransparent) {
10145
- var renderStates = this.renderStates;
10146
- if (renderStates.length < passIndex) {
10147
- throw "Pass should less than pass count.";
10148
- }
10149
- var renderState = renderStates[passIndex];
9855
+ */ _proto.setIsTransparent = function setIsTransparent(isTransparent) {
10150
9856
  var shaderData = this.shaderData;
10151
9857
  if (isTransparent) {
10152
- renderState.blendState.targetBlendState.enabled = true;
10153
- renderState.depthState.writeEnabled = false;
10154
- renderState.renderQueueType = RenderQueueType.Transparent;
9858
+ shaderData.setInt(BaseMaterial._blendEnabledProp, 1);
9859
+ shaderData.setInt(BaseMaterial._depthWriteEnabledProp, 0);
9860
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, RenderQueueType.Transparent);
10155
9861
  shaderData.enableMacro(BaseMaterial._transparentMacro);
10156
9862
  } else {
10157
- renderState.blendState.targetBlendState.enabled = false;
10158
- renderState.depthState.writeEnabled = true;
10159
- renderState.renderQueueType = shaderData.getFloat(BaseMaterial._alphaCutoffProp) ? RenderQueueType.AlphaTest : RenderQueueType.Opaque;
9863
+ shaderData.setInt(BaseMaterial._blendEnabledProp, 0);
9864
+ shaderData.setInt(BaseMaterial._depthWriteEnabledProp, 1);
9865
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, shaderData.getFloat(BaseMaterial._alphaCutoffProp) ? RenderQueueType.AlphaTest : RenderQueueType.Opaque);
10160
9866
  shaderData.disableMacro(BaseMaterial._transparentMacro);
10161
9867
  }
10162
9868
  };
10163
9869
  /**
10164
9870
  * Set the blend mode of shader pass render state.
10165
- * @param passIndex - Shader pass index
10166
9871
  * @param blendMode - Blend mode
10167
- */ _proto.setBlendMode = function setBlendMode(passIndex, blendMode) {
10168
- var renderStates = this.renderStates;
10169
- if (renderStates.length < passIndex) {
10170
- throw "Pass should less than pass count.";
10171
- }
10172
- var _renderStates_passIndex_blendState = renderStates[passIndex].blendState, target = _renderStates_passIndex_blendState.targetBlendState;
9872
+ */ _proto.setBlendMode = function setBlendMode(blendMode) {
9873
+ var shaderData = this.shaderData;
10173
9874
  switch(blendMode){
10174
9875
  case BlendMode.Normal:
10175
- target.sourceColorBlendFactor = BlendFactor.SourceAlpha;
10176
- target.destinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha;
10177
- target.sourceAlphaBlendFactor = BlendFactor.One;
10178
- target.destinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
10179
- target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
9876
+ shaderData.setInt(BaseMaterial._sourceColorBlendFactorProp, BlendFactor.SourceAlpha);
9877
+ shaderData.setInt(BaseMaterial._destinationColorBlendFactorProp, BlendFactor.OneMinusSourceAlpha);
9878
+ shaderData.setInt(BaseMaterial._sourceAlphaBlendFactorProp, BlendFactor.One);
9879
+ shaderData.setInt(BaseMaterial._destinationAlphaBlendFactorProp, BlendFactor.OneMinusSourceAlpha);
10180
9880
  break;
10181
9881
  case BlendMode.Additive:
10182
- target.sourceColorBlendFactor = BlendFactor.SourceAlpha;
10183
- target.destinationColorBlendFactor = BlendFactor.One;
10184
- target.sourceAlphaBlendFactor = BlendFactor.Zero;
10185
- target.destinationAlphaBlendFactor = BlendFactor.One;
10186
- target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
9882
+ shaderData.setInt(BaseMaterial._sourceColorBlendFactorProp, BlendFactor.SourceAlpha);
9883
+ shaderData.setInt(BaseMaterial._destinationColorBlendFactorProp, BlendFactor.One);
9884
+ shaderData.setInt(BaseMaterial._sourceAlphaBlendFactorProp, BlendFactor.Zero);
9885
+ shaderData.setInt(BaseMaterial._destinationAlphaBlendFactorProp, BlendFactor.One);
10187
9886
  break;
10188
9887
  }
10189
9888
  };
10190
9889
  /**
10191
9890
  * Set the render face of shader pass render state.
10192
- * @param passIndex - Shader pass index
10193
9891
  * @param renderFace - Render face
10194
- */ _proto.setRenderFace = function setRenderFace(passIndex, renderFace) {
10195
- var renderStates = this.renderStates;
10196
- if (renderStates.length < passIndex) {
10197
- throw "Pass should less than pass count.";
10198
- }
9892
+ */ _proto.setRenderFace = function setRenderFace(renderFace) {
9893
+ var shaderData = this.shaderData;
10199
9894
  switch(renderFace){
10200
9895
  case RenderFace.Front:
10201
- renderStates[passIndex].rasterState.cullMode = CullMode.Back;
9896
+ shaderData.setInt(BaseMaterial._rasterStateCullModeProp, CullMode.Back);
10202
9897
  break;
10203
9898
  case RenderFace.Back:
10204
- renderStates[passIndex].rasterState.cullMode = CullMode.Front;
9899
+ shaderData.setInt(BaseMaterial._rasterStateCullModeProp, CullMode.Front);
10205
9900
  break;
10206
9901
  case RenderFace.Double:
10207
- renderStates[passIndex].rasterState.cullMode = CullMode.Off;
9902
+ shaderData.setInt(BaseMaterial._rasterStateCullModeProp, CullMode.Off);
10208
9903
  break;
10209
9904
  }
10210
9905
  };
@@ -10227,7 +9922,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10227
9922
  _proto._seIsTransparent = function _seIsTransparent(value) {
10228
9923
  if (value !== this._isTransparent) {
10229
9924
  // Forward pass
10230
- this.setIsTransparent(0, value);
9925
+ this.setIsTransparent(value);
10231
9926
  // Shadow caster pass and depth only pass
10232
9927
  var shaderData = this.shaderData;
10233
9928
  if (value) {
@@ -10253,7 +9948,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10253
9948
  shaderData.enableMacro(BaseMaterial._alphaCutoffMacro);
10254
9949
  // Forward render queue
10255
9950
  var forwardQueue = isTransparent ? RenderQueueType.Transparent : RenderQueueType.AlphaTest;
10256
- this.renderStates[0].renderQueueType = forwardQueue;
9951
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, forwardQueue);
10257
9952
  // Shadow caster render queue
10258
9953
  shaderData.setFloat(BaseMaterial._shadowCasterRenderQueueProp, RenderQueueType.AlphaTest);
10259
9954
  // Depth only render queue
@@ -10262,7 +9957,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10262
9957
  shaderData.disableMacro(BaseMaterial._alphaCutoffMacro);
10263
9958
  // Forward render queue
10264
9959
  var forwardQueue1 = isTransparent ? RenderQueueType.Transparent : RenderQueueType.Opaque;
10265
- this.renderStates[0].renderQueueType = forwardQueue1;
9960
+ shaderData.setInt(BaseMaterial._renderQueueTypeProp, forwardQueue1);
10266
9961
  // Shadow caster render queue
10267
9962
  var shadowCasterQueue = isTransparent ? RenderQueueType.AlphaTest : RenderQueueType.Opaque;
10268
9963
  shaderData.setFloat(BaseMaterial._shadowCasterRenderQueueProp, shadowCasterQueue);
@@ -10273,38 +9968,6 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10273
9968
  }
10274
9969
  };
10275
9970
  _create_class(BaseMaterial, [
10276
- {
10277
- key: "shader",
10278
- get: /**
10279
- * Shader used by the material.
10280
- */ function get() {
10281
- return this._shader;
10282
- },
10283
- set: function set(value) {
10284
- var refCount = this._getReferCount();
10285
- if (refCount > 0) {
10286
- var _this__shader;
10287
- (_this__shader = this._shader) == null ? void 0 : _this__shader._addReferCount(-refCount);
10288
- value._addReferCount(refCount);
10289
- }
10290
- this._shader = value;
10291
- var renderStates = this._renderStates;
10292
- var lastStatesCount = renderStates.length;
10293
- var maxPassCount = 0;
10294
- var subShaders = value.subShaders;
10295
- for(var i = 0; i < subShaders.length; i++){
10296
- maxPassCount = Math.max(subShaders[i].passes.length, maxPassCount);
10297
- }
10298
- if (lastStatesCount < maxPassCount) {
10299
- for(var i1 = lastStatesCount; i1 < maxPassCount; i1++){
10300
- renderStates.push(new RenderState());
10301
- this.setBlendMode(i1, BlendMode.Normal);
10302
- }
10303
- } else {
10304
- renderStates.length = maxPassCount;
10305
- }
10306
- }
10307
- },
10308
9971
  {
10309
9972
  key: "isTransparent",
10310
9973
  get: /**
@@ -10326,7 +9989,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10326
9989
  },
10327
9990
  set: function set(value) {
10328
9991
  if (value !== this._blendMode) {
10329
- this.setBlendMode(0, value);
9992
+ this.setBlendMode(value);
10330
9993
  this._blendMode = value;
10331
9994
  }
10332
9995
  }
@@ -10354,7 +10017,7 @@ var BaseMaterial = /*#__PURE__*/ function(Material) {
10354
10017
  },
10355
10018
  set: function set(value) {
10356
10019
  if (value !== this._renderFace) {
10357
- this.setRenderFace(0, value);
10020
+ this.setRenderFace(value);
10358
10021
  this._renderFace = value;
10359
10022
  }
10360
10023
  }
@@ -10377,6 +10040,14 @@ BaseMaterial._emissiveColorProp = ShaderProperty.getByName("material_EmissiveCol
10377
10040
  BaseMaterial._emissiveTextureProp = ShaderProperty.getByName("material_EmissiveTexture");
10378
10041
  BaseMaterial._alphaCutoffProp = ShaderProperty.getByName("material_AlphaCutoff");
10379
10042
  BaseMaterial._alphaCutoffMacro = ShaderMacro.getByName("MATERIAL_IS_ALPHA_CUTOFF");
10043
+ BaseMaterial._blendEnabledProp = ShaderProperty.getByName("blendEnabled");
10044
+ BaseMaterial._depthWriteEnabledProp = ShaderProperty.getByName("depthWriteEnabled");
10045
+ BaseMaterial._renderQueueTypeProp = ShaderProperty.getByName("renderQueueType");
10046
+ BaseMaterial._sourceColorBlendFactorProp = ShaderProperty.getByName("sourceColorBlendFactor");
10047
+ BaseMaterial._destinationColorBlendFactorProp = ShaderProperty.getByName("destinationColorBlendFactor");
10048
+ BaseMaterial._sourceAlphaBlendFactorProp = ShaderProperty.getByName("sourceAlphaBlendFactor");
10049
+ BaseMaterial._destinationAlphaBlendFactorProp = ShaderProperty.getByName("destinationAlphaBlendFactor");
10050
+ BaseMaterial._rasterStateCullModeProp = ShaderProperty.getByName("rasterStateCullMode");
10380
10051
 
10381
10052
  /**
10382
10053
  * Blinn-phong Material.
@@ -10384,7 +10055,7 @@ BaseMaterial._alphaCutoffMacro = ShaderMacro.getByName("MATERIAL_IS_ALPHA_CUTOFF
10384
10055
  _inherits(BlinnPhongMaterial, BaseMaterial);
10385
10056
  function BlinnPhongMaterial(engine) {
10386
10057
  var _this;
10387
- _this = BaseMaterial.call(this, engine, Shader.find("blinn-phong")) || this;
10058
+ _this = BaseMaterial.call(this, engine, Shader.find("BlinnPhong")) || this;
10388
10059
  var shaderData = _this.shaderData;
10389
10060
  shaderData.enableMacro("MATERIAL_NEED_WORLD_POS");
10390
10061
  shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
@@ -10580,7 +10251,7 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
10580
10251
  _inherits(PBRMaterial, BaseMaterial1);
10581
10252
  function PBRMaterial(engine) {
10582
10253
  var _this;
10583
- _this = BaseMaterial1.call(this, engine, Shader.find("pbr")) || this, _this._anisotropyRotation = 0, _this._iridescenceRange = new engineMath.Vector2(100, 400), _this._sheenEnabled = false;
10254
+ _this = BaseMaterial1.call(this, engine, Shader.find("PBR")) || this, _this._anisotropyRotation = 0, _this._iridescenceRange = new engineMath.Vector2(100, 400), _this._sheenEnabled = false;
10584
10255
  var shaderData = _this.shaderData;
10585
10256
  shaderData.enableMacro("MATERIAL_NEED_WORLD_POS");
10586
10257
  shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
@@ -11138,7 +10809,7 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
11138
10809
  this._seIsTransparent(value);
11139
10810
  if (this.transmission > 0) {
11140
10811
  // If transmission enabled, always use transparent queue to ensure get correct opaque texture
11141
- this.renderState.renderQueueType = RenderQueueType.Transparent;
10812
+ this.shaderData.setInt("renderQueueType", RenderQueueType.Transparent);
11142
10813
  }
11143
10814
  }
11144
10815
  },
@@ -11153,7 +10824,7 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
11153
10824
  this._setAlphaCutoff(value);
11154
10825
  if (this.transmission > 0) {
11155
10826
  // If transmission enabled, always use transparent queue to ensure get correct opaque texture
11156
- this.renderState.renderQueueType = RenderQueueType.Transparent;
10827
+ this.shaderData.setInt("renderQueueType", RenderQueueType.Transparent);
11157
10828
  }
11158
10829
  }
11159
10830
  },
@@ -11170,9 +10841,19 @@ BlinnPhongMaterial._specularTextureProp = ShaderProperty.getByName("material_Spe
11170
10841
  if (!!this.shaderData.getFloat(PBRMaterial._transmissionProp) !== !!value) {
11171
10842
  if (value > 0) {
11172
10843
  this.shaderData.enableMacro(PBRMaterial._transmissionMacro);
11173
- this.renderState.renderQueueType = RenderQueueType.Transparent;
10844
+ this.shaderData.setInt("renderQueueType", RenderQueueType.Transparent);
11174
10845
  } else {
11175
10846
  this.shaderData.disableMacro(PBRMaterial._transmissionMacro);
10847
+ // Restore renderQueueType based on isTransparent / alphaCutoff state
10848
+ var queue;
10849
+ if (this._isTransparent) {
10850
+ queue = RenderQueueType.Transparent;
10851
+ } else if (this.shaderData.getFloat(BaseMaterial._alphaCutoffProp)) {
10852
+ queue = RenderQueueType.AlphaTest;
10853
+ } else {
10854
+ queue = RenderQueueType.Opaque;
10855
+ }
10856
+ this.shaderData.setInt("renderQueueType", queue);
11176
10857
  }
11177
10858
  }
11178
10859
  this.shaderData.setFloat(PBRMaterial._transmissionProp, value);
@@ -11366,7 +11047,7 @@ PBRMaterial._specularColorTextureProp = ShaderProperty.getByName("material_Specu
11366
11047
  _inherits(UnlitMaterial, BaseMaterial);
11367
11048
  function UnlitMaterial(engine) {
11368
11049
  var _this;
11369
- _this = BaseMaterial.call(this, engine, Shader.find("unlit")) || this;
11050
+ _this = BaseMaterial.call(this, engine, Shader.find("Unlit")) || this;
11370
11051
  var shaderData = _this.shaderData;
11371
11052
  shaderData.enableMacro("MATERIAL_OMIT_NORMAL");
11372
11053
  shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
@@ -11534,7 +11215,8 @@ PipelineUtils.defaultViewport = new engineMath.Vector4(0, 0, 1, 1);
11534
11215
  program.uploadAll(program.rendererUniformBlock, rendererShaderData);
11535
11216
  program.uploadAll(program.materialUniformBlock, blitMaterial.shaderData);
11536
11217
  program.uploadUnGroupTextures();
11537
- (pass._renderState || blitMaterial.renderState)._applyStates(engine, false, pass._renderStateDataMap, blitMaterial.shaderData);
11218
+ var renderState = pass._renderState;
11219
+ renderState._applyStates(engine, false, pass._renderStateDataMap, blitMaterial.shaderData);
11538
11220
  rhi.drawPrimitive(blitMesh._primitive, blitMesh.subMesh, program);
11539
11221
  rendererShaderData.setTexture(Blitter._blitTextureProperty, null);
11540
11222
  };
@@ -11555,8 +11237,6 @@ Blitter._defaultScaleOffset = new engineMath.Vector4(1, 1, 0, 0);
11555
11237
  this.engine = engine;
11556
11238
  };
11557
11239
 
11558
- var blitVs = "attribute vec4 POSITION_UV;\nvarying vec2 v_uv;\n\nvoid main() {\t\n\tgl_Position = vec4(POSITION_UV.xy, 0.0, 1.0);\t\n\tv_uv = POSITION_UV.zw;\n}"; // eslint-disable-line
11559
-
11560
11240
  /**
11561
11241
  * Ambient occlusion quality levels that control the balance between visual quality and performance.
11562
11242
  */ var AmbientOcclusionQuality = /*#__PURE__*/ function(AmbientOcclusionQuality) {
@@ -11566,10 +11246,6 @@ var blitVs = "attribute vec4 POSITION_UV;\nvarying vec2 v_uv;\n\nvoid main() {\t
11566
11246
  return AmbientOcclusionQuality;
11567
11247
  }({});
11568
11248
 
11569
- var bilateralBlurFS = "#include <common>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_SourceScaleOffset; \nuniform float material_farPlaneOverEdgeDistance;\n#if SSAO_QUALITY == 0\n #define BLUR_SAMPLE_COUNT 3\n#elif SSAO_QUALITY == 1\n #define BLUR_SAMPLE_COUNT 6\n#elif SSAO_QUALITY == 2\n #define BLUR_SAMPLE_COUNT 12\n#endif\n\nuniform float material_kernel[12]; // Sample weights for bilateral blur\n\nfloat bilateralWeight(float depth, float sampleDepth) {\n float diff = (sampleDepth - depth) * material_farPlaneOverEdgeDistance;\n return max(0.0, 1.0 - diff * diff);\n}\n\nhighp float unpack(highp vec2 depth) {\n // depth here only has 8-bits of precision, but the unpacked depth is highp\n // this is equivalent to (x8 * 256 + y8) / 65535, which gives a value between 0 and 1\n return (depth.x * (256.0 / 257.0) + depth.y * (1.0 / 257.0));\n}\n\nvoid tap(const sampler2D saoTexture,\n inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {\n vec4 data = texture2D(saoTexture, position);\n // bilateral sample\n float bilateral = weight * bilateralWeight(depth, unpack(data.gb));\n sum += data.r * bilateral;\n totalWeight += bilateral;\n}\n\nvoid main(){\n mediump vec4 data = texture2D(renderer_BlitTexture, v_uv);\n float depth = unpack(data.gb);\n\n // Weight of the center pixel from the Gaussian kernel (typically 1.0)\n float totalWeight = material_kernel[0];\n float sum = data.r * totalWeight;\n \n vec2 offset = renderer_SourceScaleOffset.zw;\n for (int i = 1; i < BLUR_SAMPLE_COUNT; i++) {\n float weight = material_kernel[i];\n tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v_uv + offset);\n tap(renderer_BlitTexture, sum, totalWeight, weight, depth, v_uv - offset);\n offset += renderer_SourceScaleOffset.zw;\n }\n\n float ao = sum * (1.0 / totalWeight);\n\n // simple dithering helps a lot (assumes 8 bits target)\n // this is most useful with high quality/large blurs\n ao += ((interleavedGradientNoise(gl_FragCoord.xy) - 0.5) / 255.0);\n gl_FragColor = vec4(ao, data.gb, 1.0);\n\n}\n\n"; // eslint-disable-line
11570
-
11571
- var scalableAmbientOcclusionFS = "// Ambient Occlusion, largely inspired from:\n// \"The Alchemy Screen-Space Ambient Obscurance Algorithm\" by Morgan McGuire\n// \"Scalable Ambient Obscurance\" by Morgan McGuire, Michael Mara and David Luebke\n// https://research.nvidia.com/sites/default/files/pubs/2012-06_Scalable-Ambient-Obscurance/McGuire12SAO.pdf\n\n#include <common>\n\nvarying vec2 v_uv;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\nuniform highp sampler2D renderer_BlitTexture; // Camera_DepthTexture\n\n// float inc = (1.0f / (SAMPLE_COUNT - 0.5f)) * SPIRAL_TURNS * 2.0 * PI\n// const vec2 angleIncCosSin = vec2(cos(inc), sin(inc))\n#if SSAO_QUALITY == 0\n #define SAMPLE_COUNT 7.0\n #define SPIRAL_TURNS 3.0\n const vec2 angleIncCosSin = vec2(-0.971148, 0.238227);\n#elif SSAO_QUALITY == 1\n #define SAMPLE_COUNT 11.0\n #define SPIRAL_TURNS 6.0\n const vec2 angleIncCosSin = vec2(-0.896127, -0.443780);\n#elif SSAO_QUALITY == 2\n #define SAMPLE_COUNT 16.0\n #define SPIRAL_TURNS 7.0\n const vec2 angleIncCosSin = vec2(-0.966846, 0.255311);\n#endif\n\nuniform float material_invRadiusSquared; // Inverse of the squared radius\nuniform float material_minHorizonAngleSineSquared; // Minimum horizon angle sine squared\nuniform float material_intensity; // Intensity of the ambient occlusion\nuniform float material_projectionScaleRadius;\nuniform float material_bias; // Bias to avoid self-occlusion\nuniform float material_peak2; // Peak value to avoid singularities\nuniform float material_power; // Exponent to convert occlusion to visibility\nuniform vec2 material_invProjScaleXY; //invProjection[0][0] * 2, invProjection[1][1] * 2\n\n\nvec3 computeViewSpacePosition(vec2 uv, float linearDepth, vec2 invProjScaleXY) {\n #ifdef CAMERA_ORTHOGRAPHIC\n return vec3((vec2(0.5) - uv) * invProjScaleXY , linearDepth);\n #else\n return vec3((vec2(0.5) - uv) * invProjScaleXY * linearDepth, linearDepth);\n #endif\n}\n\nfloat depthToViewZ(float depth) {\n return -remapDepthBufferEyeDepth(depth);\n}\n\n// reconstructing normal from depth buffer\n// https://atyuwen.github.io/posts/normal-reconstruction\n// https://wickedengine.net/2019/09/22/improved-normal-reconstruction-from-depth/\nvec3 computeViewSpaceNormal(vec2 uv, highp sampler2D depthTexture, float depth, vec3 viewPos, vec2 texel, vec2 invProjScaleXY) {\n vec3 normal = vec3(0.0);\n#if SSAO_QUALITY == 0 || SSAO_QUALITY == 1\n vec2 uvdx = uv + vec2(texel.x, 0.0);\n vec2 uvdy = uv + vec2(0.0, texel.y);\n\n float depthX = texture2D(depthTexture, uvdx).r;\n float depthY = texture2D(depthTexture, uvdy).r;\n\n vec3 px = computeViewSpacePosition(uvdx, depthToViewZ(depthX), invProjScaleXY);\n vec3 py = computeViewSpacePosition(uvdy, depthToViewZ(depthY), invProjScaleXY);\n\n vec3 dpdx = px - viewPos;\n vec3 dpdy = py - viewPos;\n\n normal = normalize(cross(dpdx, dpdy));\n\n#elif SSAO_QUALITY == 2\n vec2 dx = vec2(texel.x, 0.0);\n vec2 dy = vec2(0.0, texel.y);\n \n vec4 H;\n H.x = texture2D(depthTexture, uv - dx).r; // left\n H.y = texture2D(depthTexture, uv + dx).r; // right\n H.z = texture2D(depthTexture, uv - dx * 2.0).r; // left2\n H.w = texture2D(depthTexture, uv + dx * 2.0).r; // right2\n \n // Calculate horizontal edge weights\n vec2 horizontalEdgeWeights = abs((2.0 * H.xy - H.zw) - depth);\n\n vec3 pos_l = computeViewSpacePosition(uv - dx, depthToViewZ(H.x), invProjScaleXY);\n vec3 pos_r = computeViewSpacePosition(uv + dx, depthToViewZ(H.y), invProjScaleXY);\n vec3 dpdx = (horizontalEdgeWeights.x < horizontalEdgeWeights.y) ? (viewPos - pos_l) : (pos_r - viewPos);\n\n // Sample depths for vertical edge detection\n vec4 V;\n V.x = texture2D(depthTexture, uv - dy).r; // down\n V.y = texture2D(depthTexture, uv + dy).r; // up\n V.z = texture2D(depthTexture, uv - dy * 2.0).r; // down2\n V.w = texture2D(depthTexture, uv + dy * 2.0).r; // up2\n\n // Calculate vertical edge weights\n vec2 verticalEdgeWeights = abs((2.0 * V.xy - V.zw) - depth);\n vec3 pos_d = computeViewSpacePosition(uv - dy, depthToViewZ(V.x), invProjScaleXY);\n vec3 pos_u = computeViewSpacePosition(uv + dy, depthToViewZ(V.y), invProjScaleXY);\n vec3 dpdy = (verticalEdgeWeights.x < verticalEdgeWeights.y) ? (viewPos - pos_d) : (pos_u - viewPos);\n normal = normalize(cross(dpdx, dpdy));\n #endif\n return normal;\n\n}\n\nvec3 tapLocation(float i, const float noise) {\n float offset = ((2.0 * PI) * 2.4) * noise;\n float angle = ((i / SAMPLE_COUNT) * SPIRAL_TURNS) * (2.0 * PI) + offset;\n float radius = (i + noise + 0.5) / SAMPLE_COUNT;\n return vec3(cos(angle), sin(angle), radius * radius);\n}\n\nvec2 startPosition(const float noise) {\n float angle = ((2.0 * PI) * 2.4) * noise;\n return vec2(cos(angle), sin(angle));\n}\n\nmat2 tapAngleStep() {\n vec2 t = angleIncCosSin;\n return mat2(t.x, t.y, -t.y, t.x);\n}\n\nvec3 tapLocationFast(float i, vec2 p, const float noise) {\n float radius = (i + noise + 0.5) / SAMPLE_COUNT;\n return vec3(p, radius * radius);\n}\n\nvoid computeAmbientOcclusionSAO(inout float occlusion, float i, float ssDiskRadius, vec2 uv, vec3 originPosition, vec3 normal,\n vec2 tapPosition, float noise) {\n\n vec3 tap = tapLocationFast(i, tapPosition, noise);\n\n float ssRadius = max(1.0, tap.z * ssDiskRadius); // at least 1 pixel screen-space radius\n\n vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * renderer_texelSize.xy;\n\n float occlusionDepth = texture2D(renderer_BlitTexture, uvSamplePos).r;\n float linearOcclusionDepth = depthToViewZ(occlusionDepth);\n // “p” is the position after spiral sampling\n vec3 p = computeViewSpacePosition(uvSamplePos, linearOcclusionDepth, material_invProjScaleXY);\n\n // now we have the sample, compute AO\n vec3 v = p - originPosition; // sample vector\n float vv = dot(v, v); // squared distance\n float vn = dot(v, normal); // distance * cos(v, normal)\n\n // discard samples that are outside of the radius, preventing distant geometry to\n // cast shadows -- there are many functions that work and choosing one is an artistic\n // decision.\n float weight = pow(max(0.0, 1.0 - vv * material_invRadiusSquared), 2.0);\n\n // discard samples that are too close to the horizon to reduce shadows cast by geometry\n // not sufficently tessellated. The goal is to discard samples that form an angle 'beta'\n // smaller than 'epsilon' with the horizon. We already have dot(v,n) which is equal to the\n // sin(beta) * |v|. So the test simplifies to vn^2 < vv * sin(epsilon)^2.\n weight *= step(vv * material_minHorizonAngleSineSquared, vn * vn);\n\n // Calculate the contribution of a single sampling point to Ambient Occlusion\n float sampleOcclusion = max(0.0, vn + (originPosition.z * material_bias)) / (vv + material_peak2);\n occlusion += weight * sampleOcclusion;\n}\n\nvoid scalableAmbientObscurance(vec2 uv, vec3 origin, vec3 normal, out float obscurance) {\n float noise = interleavedGradientNoise(gl_FragCoord.xy);\n vec2 tapPosition = startPosition(noise);\n mat2 angleStep = tapAngleStep();\n\n // Choose the screen-space sample radius\n // proportional to the projected area of the sphere\n float ssDiskRadius = -(material_projectionScaleRadius / origin.z);\n\n // Accumulate the occlusion amount of all sampling points\n obscurance = 0.0;\n for (float i = 0.0; i < SAMPLE_COUNT; i += 1.0) {\n computeAmbientOcclusionSAO(obscurance, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);\n tapPosition = angleStep * tapPosition;\n }\n obscurance = sqrt(obscurance * material_intensity);\n}\n\nvec2 pack(highp float normalizedDepth) {\n highp float z = clamp(normalizedDepth, 0.0, 1.0);\n highp float t = floor(256.0 * z);\n mediump float hi = t * (1.0 / 256.0);\n mediump float lo = (256.0 * z) - t;\n return vec2(hi, lo);\n}\n\n\nvoid main(){\n float depth = texture2D(renderer_BlitTexture, v_uv).r;\n float z = depthToViewZ(depth);\n\n // Reconstruct view space position from depth\n vec3 positionVS = computeViewSpacePosition(v_uv, z, material_invProjScaleXY);\n\n // Compute normal\n vec3 normal = computeViewSpaceNormal(v_uv, renderer_BlitTexture, depth, positionVS, renderer_texelSize.xy, material_invProjScaleXY);\n\n float occlusion = 0.0;\n scalableAmbientObscurance(v_uv, positionVS, normal, occlusion);\n\n // Occlusion to visibility\n float aoVisibility = pow(clamp(1.0 - occlusion, 0.0, 1.0), material_power);\n\n gl_FragColor = vec4(aoVisibility, pack(-positionVS.z/camera_ProjectionParams.z), 1.0);\n}\n\n"; // eslint-disable-line
11572
-
11573
11249
  /**
11574
11250
  * @internal
11575
11251
  * Scalable Ambient Obscurance render pass.
@@ -11699,7 +11375,7 @@ var scalableAmbientOcclusionFS = "// Ambient Occlusion, largely inspired from:\n
11699
11375
  };
11700
11376
  return ScalableAmbientObscurancePass;
11701
11377
  }(PipelinePass);
11702
- ScalableAmbientObscurancePass.SHADER_NAME = "ScalableAmbientOcclusion";
11378
+ ScalableAmbientObscurancePass.SHADER_NAME = "Lighting/ScalableAmbientOcclusion";
11703
11379
  ScalableAmbientObscurancePass._invRadiusSquaredProp = ShaderProperty.getByName("material_invRadiusSquared");
11704
11380
  ScalableAmbientObscurancePass._intensityProp = ShaderProperty.getByName("material_intensity");
11705
11381
  ScalableAmbientObscurancePass._projectionScaleRadiusProp = ShaderProperty.getByName("material_projectionScaleRadius");
@@ -11711,10 +11387,6 @@ ScalableAmbientObscurancePass._invProjScaleXYProp = ShaderProperty.getByName("ma
11711
11387
  // Shader properties for bilateral blur
11712
11388
  ScalableAmbientObscurancePass._farPlaneOverEdgeDistanceProp = ShaderProperty.getByName("material_farPlaneOverEdgeDistance");
11713
11389
  ScalableAmbientObscurancePass._kernelProp = ShaderProperty.getByName("material_kernel");
11714
- Shader.create(ScalableAmbientObscurancePass.SHADER_NAME, [
11715
- new ShaderPass("ScalableAmbientOcclusion", blitVs, scalableAmbientOcclusionFS),
11716
- new ShaderPass("BilateralBlur", blitVs, bilateralBlurFS)
11717
- ]);
11718
11390
 
11719
11391
  /**
11720
11392
  * Represents a parameter of a post process effect.
@@ -11953,14 +11625,6 @@ Shader.create(ScalableAmbientObscurancePass.SHADER_NAME, [
11953
11625
  return PostProcessEffect;
11954
11626
  }();
11955
11627
 
11956
- var fragBlurH = "#include <PostCommon>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n\tvec2 texelSize = renderer_texelSize.xy * 2.0;\n\n // 9-tap gaussian blur on the downsampled source\n mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 4.0, 0.0));\n mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 3.0, 0.0));\n mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 2.0, 0.0));\n mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(texelSize.x * 1.0, 0.0));\n mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v_uv);\n mediump vec4 c5 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 1.0, 0.0));\n mediump vec4 c6 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 2.0, 0.0));\n mediump vec4 c7 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 3.0, 0.0));\n mediump vec4 c8 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(texelSize.x * 4.0, 0.0));\n\n gl_FragColor = c0 * 0.01621622 + c1 * 0.05405405 + c2 * 0.12162162 + c3 * 0.19459459\n + c4 * 0.22702703\n + c5 * 0.19459459 + c6 * 0.12162162 + c7 * 0.05405405 + c8 * 0.01621622;\n}"; // eslint-disable-line
11957
-
11958
- var fragBlurV = "#include <PostCommon>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n vec2 texelSize = renderer_texelSize.xy;\n\n // Optimized bilinear 5-tap gaussian on the same-sized source (9-tap equivalent)\n mediump vec4 c0 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(0.0, texelSize.y * 3.23076923));\n mediump vec4 c1 = texture2DSRGB(renderer_BlitTexture, v_uv - vec2(0.0, texelSize.y * 1.38461538));\n mediump vec4 c2 = texture2DSRGB(renderer_BlitTexture, v_uv);\n mediump vec4 c3 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(0.0, texelSize.y * 1.38461538));\n mediump vec4 c4 = texture2DSRGB(renderer_BlitTexture, v_uv + vec2(0.0, texelSize.y * 3.23076923));\n\n gl_FragColor = c0 * 0.07027027 + c1 * 0.31621622\n + c2 * 0.22702703\n + c3 * 0.31621622 + c4 * 0.07027027;\n}"; // eslint-disable-line
11959
-
11960
- var fragPrefilter = "#include <PostCommon>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 material_BloomParams; // x: threshold (linear), y: threshold knee, z: scatter\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n\t#ifdef BLOOM_HQ\n vec2 texelSize = renderer_texelSize.xy;\n mediump vec4 A = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, -1.0));\n mediump vec4 B = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.0, -1.0));\n mediump vec4 C = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, -1.0));\n mediump vec4 D = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-0.5, -0.5));\n mediump vec4 E = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.5, -0.5));\n mediump vec4 F = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, 0.0));\n mediump vec4 G = texture2DSRGB(renderer_BlitTexture, v_uv);\n mediump vec4 H = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, 0.0));\n mediump vec4 I = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-0.5, 0.5));\n mediump vec4 J = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.5, 0.5));\n mediump vec4 K = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(-1.0, 1.0));\n mediump vec4 L = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(0.0, 1.0));\n mediump vec4 M = texture2DSRGB(renderer_BlitTexture, v_uv + texelSize * vec2(1.0, 1.0));\n\n mediump vec2 scale = vec2(0.5, 0.125);\n mediump vec2 div = (1.0 / 4.0) * scale;\n\n mediump vec4 samplerColor = (D + E + I + J) * div.x;\n samplerColor += (A + B + G + F) * div.y;\n samplerColor += (B + C + H + G) * div.y;\n samplerColor += (F + G + L + K) * div.y;\n samplerColor += (G + H + M + L) * div.y;\n #else\n mediump vec4 samplerColor = texture2DSRGB(renderer_BlitTexture, v_uv);\n #endif\n\n mediump vec3 color = samplerColor.rgb;\n\n // User controlled clamp to limit crazy high broken spec\n color = min(color, HALF_MAX);\n\n // Thresholding\n mediump float brightness = max3(color);\n float threshold = material_BloomParams.x;\n float thresholdKnee = material_BloomParams.y;\n mediump float softness = clamp(brightness - threshold + thresholdKnee, 0.0, 2.0 * thresholdKnee);\n softness = (softness * softness) / (4.0 * thresholdKnee + 1e-4);\n mediump float multiplier = max(brightness - threshold, softness) / max(brightness, 1e-4);\n color *= multiplier;\n\n // Clamp colors to positive once in prefilter. Encode can have a sqrt, and sqrt(-x) == NaN. Up/Downsample passes would then spread the NaN.\n color = max(color, 0.0);\n\n // Bloom is addtive blend mode, we should set alpha 0 to avoid browser background color dark when canvas alpha and premultiplyAlpha is true\n gl_FragColor = vec4(color, 0.0);\n}\n"; // eslint-disable-line
11961
-
11962
- var fragUpsample = "#include <PostCommon>\n#include <Filtering>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform sampler2D material_lowMipTexture;\nuniform vec4 material_BloomParams; // x: threshold (linear), y: threshold knee, z: scatter\nuniform vec4 material_lowMipTexelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvoid main(){\n mediump vec4 highMip = texture2DSRGB(renderer_BlitTexture, v_uv);\n\n #ifdef BLOOM_HQ\n mediump vec4 lowMip = sampleTexture2DBicubic(material_lowMipTexture, v_uv, material_lowMipTexelSize);\n #else\n mediump vec4 lowMip = texture2DSRGB(material_lowMipTexture, v_uv);\n #endif\n \n gl_FragColor = mix(highMip, lowMip, material_BloomParams.z);\n}"; // eslint-disable-line
11963
-
11964
11628
  /**
11965
11629
  * This controls the size of the bloom texture.
11966
11630
  */ var BloomDownScaleMode = /*#__PURE__*/ function(BloomDownScaleMode) {
@@ -11999,7 +11663,7 @@ var BloomEffect = /*#__PURE__*/ function(PostProcessEffect) {
11999
11663
  };
12000
11664
  return BloomEffect;
12001
11665
  }(PostProcessEffect);
12002
- BloomEffect.SHADER_NAME = "PostProcessEffect Bloom";
11666
+ BloomEffect.SHADER_NAME = "PostProcess/Bloom";
12003
11667
  // Bloom shader properties
12004
11668
  /** @internal */ BloomEffect._maxIterations = 6;
12005
11669
  /** @internal */ BloomEffect._hqMacro = ShaderMacro.getByName("BLOOM_HQ");
@@ -12017,12 +11681,6 @@ BloomEffect.SHADER_NAME = "PostProcessEffect Bloom";
12017
11681
  /** @internal */ BloomEffect._bloomIntensityParams = ShaderProperty.getByName("material_BloomIntensityParams") // x: bloom intensity, y: dirt intensity
12018
11682
  ;
12019
11683
  /** @internal */ BloomEffect._dirtTilingOffsetProp = ShaderProperty.getByName("material_BloomDirtTilingOffset");
12020
- Shader.create(BloomEffect.SHADER_NAME, [
12021
- new ShaderPass("Bloom Prefilter", blitVs, fragPrefilter),
12022
- new ShaderPass("Bloom Blur Horizontal", blitVs, fragBlurH),
12023
- new ShaderPass("Bloom Blur Vertical", blitVs, fragBlurV),
12024
- new ShaderPass("Bloom Upsample", blitVs, fragUpsample)
12025
- ]);
12026
11684
 
12027
11685
  /**
12028
11686
  * Options to select a tonemapping algorithm to use.
@@ -15285,24 +14943,6 @@ PostProcessManager._tempVector3 = new engineMath.Vector3();
15285
14943
  return PostProcessPass;
15286
14944
  }(EngineObject);
15287
14945
 
15288
- var Filtering = "#ifndef FILTERING\n#define FILTERING\n\nvec2 bSpline3MiddleLeft(vec2 x){\n return 0.16666667 + x * (0.5 + x * (0.5 - x * 0.5));\n}\n\nvec2 bSpline3MiddleRight(vec2 x){\n return 0.66666667 + x * (-1.0 + 0.5 * x) * x;\n}\n\nvec2 bSpline3Rightmost(vec2 x){\n return 0.16666667 + x * (-0.5 + x * (0.5 - x * 0.16666667));\n}\n\n// Compute weights & offsets for 4x bilinear taps for the bicubic B-Spline filter.\n// The fractional coordinate should be in the [0, 1] range (centered on 0.5).\n// Inspired by: http://vec3.ca/bicubic-filtering-in-fewer-taps/\nvoid bicubicFilter(vec2 fracCoord, out vec2 weights[2], out vec2 offsets[2]){\n vec2 r = bSpline3Rightmost(fracCoord);\n vec2 mr = bSpline3MiddleRight(fracCoord);\n vec2 ml = bSpline3MiddleLeft(fracCoord);\n vec2 l = 1.0 - mr - ml - r;\n\n weights[0] = r + mr;\n weights[1] = ml + l;\n offsets[0] = -1.0 + mr / weights[0];\n offsets[1] = 1.0 + l / weights[1];\n}\n\n\n// texSize: (1/width, 1/height, width, height)\nvec4 sampleTexture2DBicubic(sampler2D tex, vec2 coord, vec4 texSize){\n\tvec2 xy = coord * texSize.zw + 0.5;\n vec2 ic = floor(xy);\n vec2 fc = fract(xy);\n\n vec2 weights[2], offsets[2];\n bicubicFilter(fc, weights, offsets);\n\n return weights[0].y * (weights[0].x * texture2DSRGB(tex, (ic + vec2(offsets[0].x, offsets[0].y) - 0.5) * texSize.xy) +\n \tweights[1].x * texture2DSRGB(tex, (ic + vec2(offsets[1].x, offsets[0].y) - 0.5) * texSize.xy)) +\n weights[1].y * (weights[0].x * texture2DSRGB(tex, (ic + vec2(offsets[0].x, offsets[1].y) - 0.5) * texSize.xy) +\n weights[1].x * texture2DSRGB(tex, (ic + vec2(offsets[1].x, offsets[1].y) - 0.5) * texSize.xy));\n}\n\n\n#endif"; // eslint-disable-line
15289
-
15290
- var PostCommon = "#ifndef POST_COMMON\n#define POST_COMMON\n\n#include <common>\n#define FLT_MIN 1.175494351e-38 // Minimum normalized positive floating-point number\n#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\n#define HALF_MAX 65504.0 // (2 - 2^-10) * 2^15\n\nfloat min3(vec3 val) { return min(min(val.x, val.y), val.z); }\nfloat max3(vec3 val) { return max(max(val.x, val.y), val.z); }\n\nconst float INVERT_LOG10 = 0.43429448190325176;\n\nfloat log10(float x){\n return log(x) * INVERT_LOG10;\n}\n\n#endif"; // eslint-disable-line
15291
-
15292
- var ACESTonemapping = "#include <ColorTransform>\n#include <RRT>\n#include <ODT>\n\nvec3 ACESTonemap(vec3 color){\n vec3 aces = sRGB_2_AP0 * color;\n \n // --- Glow module --- //\n mediump float saturation = rgb_2_saturation(aces);\n mediump float ycIn = rgb_2_yc(aces);\n mediump float s = sigmoid_shaper((saturation - 0.4) / 0.2);\n float addedGlow = 1.0 + glow_fwd(ycIn, RRT_GLOW_GAIN * s, RRT_GLOW_MID);\n aces *= addedGlow;\n\n // --- Red modifier --- //\n mediump float hue = rgb_2_hue(vec3(aces));\n mediump float centeredHue = center_hue(hue, RRT_RED_HUE);\n float hueWeight = smoothstep(0.0, 1.0, 1.0 - abs(2.0 * centeredHue / RRT_RED_WIDTH));\n hueWeight *= hueWeight;\n\n aces.r += hueWeight * saturation * (RRT_RED_PIVOT - aces.r) * (1.0 - RRT_RED_SCALE);\n\n // --- ACES to RGB rendering space --- //\n vec3 acescg = max(AP0_2_AP1_MAT * aces, 0.0);\n\n // --- Global desaturation --- //\n acescg = mix(vec3(dot(acescg, AP1_RGB2Y)), acescg, RRT_SAT_FACTOR);\n\n // Apply RRT and ODT\n // https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl\n const float a = 0.0245786;\n const float b = 0.000090537;\n const float c = 0.983729;\n const float d = 0.4329510;\n const float e = 0.238081;\n\n // To reduce the likelyhood of extremely large values, we avoid using the x^2 term and therefore\n // divide numerator and denominator by it. This will lead to the constant factors of the\n // quadratic in the numerator and denominator to be divided by x; we add a tiny epsilon to avoid divide by 0.\n vec3 rcpAcesCG = 1.0 / (acescg + FLT_MIN);\n mediump vec3 rgbPost = (acescg + a - b * rcpAcesCG) /\n (acescg * c + d + e * rcpAcesCG);\n\n // Apply gamma adjustment to compensate for dim surround\n vec3 linearCV = darkSurround_to_dimSurround(rgbPost);\n\n // Apply desaturation to compensate for luminance difference\n linearCV = mix(vec3(dot(linearCV, AP1_RGB2Y)), linearCV, ODT_SAT_FACTOR);\n\n // Convert to display primary encoding\n // Rendering space RGB to XYZ\n vec3 XYZ = AP1_2_XYZ_MAT * linearCV;\n\n // Apply CAT from ACES white point to assumed observer adapted white point\n XYZ = D60_2_D65_CAT * XYZ;\n\n // CIE XYZ to display primaries\n linearCV = XYZ_2_REC709_MAT * XYZ;\n\n return linearCV;\n\n}"; // eslint-disable-line
15293
-
15294
- var ColorTransform = "#ifndef COLOR_TRANSFORM\n#define COLOR_TRANSFORM\n\n// Precomputed matrices (pre-transposed)\n// See https://github.com/ampas/aces-dev/blob/master/transforms/ctl/README-MATRIX.md\n \n const mediump mat3 sRGB_2_AP0 = mat3(\n 0.4397010, 0.0897923, 0.0175440,\n 0.3829780, 0.8134230, 0.1115440,\n 0.1773350, 0.0967616, 0.8707040\n );\n\n const mediump mat3 AP1_2_AP0_MAT = mat3(\n vec3(0.6954522414, 0.0447945634, -0.0055258826),\n vec3(0.1406786965, 0.8596711185, 0.0040252103),\n vec3(0.1638690622, 0.0955343182, 1.0015006723)\n );\n\n const mediump mat3 AP0_2_AP1_MAT = mat3(\n\tvec3(1.4514393161, -0.0765537734, 0.0083161484),\n vec3(-0.2365107469, 1.1762296998, -0.0060324498),\n vec3(-0.2149285693, -0.0996759264, 0.9977163014)\n );\n\n const mediump mat3 AP1_2_XYZ_MAT = mat3(\n vec3(0.6624541811, 0.2722287168, -0.0055746495),\n vec3(0.1340042065, 0.6740817658, 0.0040607335),\n vec3(0.1561876870, 0.0536895174, 1.0103391003)\n );\n\n const mediump mat3 XYZ_2_AP1_MAT = mat3(\n vec3(1.6410233797, -0.6636628587, 0.0117218943),\n vec3(-0.3248032942, 1.6153315917, -0.0082844420),\n vec3(-0.2364246952, 0.0167563477, 0.9883948585)\n );\n\n const mediump mat3 D60_2_D65_CAT = mat3(\n vec3(0.987224, -0.00759836, 0.00307257),\n vec3(-0.00611327, 1.00186, -0.00509595),\n vec3(0.0159533, 0.00533002, 1.08168)\n );\n\n const mediump mat3 XYZ_2_REC709_MAT = mat3(\n vec3(3.2409699419, -0.9692436363, 0.0556300797),\n vec3(-1.5373831776, 1.8759675015, -0.2039769589),\n vec3(-0.498610760, 0.0415550574, 1.0569715142)\n );\n\n const mediump vec3 AP1_RGB2Y = vec3(0.2722287168, 0.6740817658, 0.0536895174);\n\n mediump float rgb_2_saturation(mediump vec3 rgb){\n const mediump float TINY = 1e-4;\n mediump float mi = min3(rgb);\n mediump float ma = max3(rgb);\n return (max(ma, TINY) - max(mi, TINY)) / max(ma, 1e-2);\n }\n\n mediump float rgb_2_yc(mediump vec3 rgb){\n const mediump float ycRadiusWeight = 1.75;\n\n // Converts RGB to a luminance proxy, here called YC\n // YC is ~ Y + K * Chroma\n // Constant YC is a cone-shaped surface in RGB space, with the tip on the\n // neutral axis, towards white.\n // YC is normalized: RGB 1 1 1 maps to YC = 1\n //\n // ycRadiusWeight defaults to 1.75, although can be overridden in function\n // call to rgb_2_yc\n // ycRadiusWeight = 1 -> YC for pure cyan, magenta, yellow == YC for neutral\n // of same value\n // ycRadiusWeight = 2 -> YC for pure red, green, blue == YC for neutral of\n // same value.\n\n mediump float r = rgb.x;\n mediump float g = rgb.y;\n mediump float b = rgb.z;\n mediump float k = b * (b - g) + g * (g - r) + r * (r - b);\n k = max(k, 0.0); // Clamp to avoid precision issue causing k < 0, making sqrt(k) undefined\n float chroma = k == 0.0 ? 0.0 : sqrt(k); // Avoid NaN\n\n return (b + g + r + ycRadiusWeight * chroma) / 3.0;\n }\n\n mediump float rgb_2_hue(mediump vec3 rgb){\n // Returns a geometric hue angle in degrees (0-360) based on RGB values.\n // For neutral colors, hue is undefined and the function will return a quiet NaN value.\n mediump float hue;\n if (rgb.x == rgb.y && rgb.y == rgb.z){\n hue = 0.0; // RGB triplets where RGB are equal have an undefined hue\n } else{\n hue = (180.0 / PI) * atan(sqrt(3.0) * (rgb.y - rgb.z), 2.0 * rgb.x - rgb.y - rgb.z);\n }\n\n if (hue < 0.0){\n hue = hue + 360.0;\n } \n\n return hue;\n }\n\n mediump float center_hue(mediump float hue, mediump float centerH){\n mediump float hueCentered = hue - centerH;\n if (hueCentered < -180.0){\n hueCentered = hueCentered + 360.0;\n } else if (hueCentered > 180.0){\n hueCentered = hueCentered - 360.0;\n } \n\n return hueCentered;\n }\n\n\n\n#endif"; // eslint-disable-line
15295
-
15296
- var ODT = "#include <Tonescale>\n\n// Output Device Transform - RGB computer monitor\n\nconst float CINEMA_WHITE = 48.0;\nconst float CINEMA_BLACK = 0.02; // CINEMA_WHITE / 2400.0;\nconst float ODT_SAT_FACTOR = 0.93;\n\nmediump vec3 Y_2_linCV(mediump vec3 Y, mediump float Ymax, mediump float Ymin){\n return (Y - Ymin) / (Ymax - Ymin);\n}\n\nmediump vec3 XYZ_2_xyY(mediump vec3 XYZ){\n mediump float divisor = max(dot(XYZ, vec3(1.0)), 1e-4);\n return vec3(XYZ.xy / divisor, XYZ.y);\n}\n\nmediump vec3 xyY_2_XYZ(mediump vec3 xyY){\n mediump float m = xyY.z / max(xyY.y, 1e-4);\n mediump vec3 XYZ = vec3(xyY.xz, (1.0 - xyY.x - xyY.y));\n XYZ.xz *= m;\n return XYZ;\n}\n\nconst mediump float DIM_SURROUND_GAMMA = 0.9811;\n\nmediump vec3 darkSurround_to_dimSurround(mediump vec3 linearCV){\n // Extra conversions to float3/vec3 are required to avoid floating-point precision issues on some platforms.\n\n mediump vec3 XYZ = AP1_2_XYZ_MAT * linearCV;\n mediump vec3 xyY = XYZ_2_xyY(XYZ);\n xyY.z = clamp(xyY.z, 0.0, HALF_MAX);\n xyY.z = pow(xyY.z, DIM_SURROUND_GAMMA);\n XYZ = xyY_2_XYZ(xyY);\n\n return XYZ_2_AP1_MAT * XYZ;\n}\n\n//\n// Summary :\n// This transform is intended for mapping OCES onto a desktop computer monitor\n// typical of those used in motion picture visual effects production. These\n// monitors may occasionally be referred to as \"sRGB\" displays, however, the\n// monitor for which this transform is designed does not exactly match the\n// specifications in IEC 61966-2-1:1999.\n//\n// The assumed observer adapted white is D65, and the viewing environment is\n// that of a dim surround.\n//\n// The monitor specified is intended to be more typical of those found in\n// visual effects production.\n//\n// Device Primaries :\n// Primaries are those specified in Rec. ITU-R BT.709\n// CIE 1931 chromaticities: x y Y\n// Red: 0.64 0.33\n// Green: 0.3 0.6\n// Blue: 0.15 0.06\n// White: 0.3127 0.329 100 cd/m^2\n//\n// Display EOTF :\n// The reference electro-optical transfer function specified in\n// IEC 61966-2-1:1999.\n//\n// Signal Range:\n// This transform outputs full range code values.\n//\n// Assumed observer adapted white point:\n// CIE 1931 chromaticities: x y\n// 0.3127 0.329\n//\n\n// Viewing Environment:\n// This ODT has a compensation for viewing environment variables more typical\n// of those associated with video mastering.\n//\nmediump vec3 ODT_RGBmonitor_100nits_dim(mediump vec3 oces){\n // The metal compiler does not optimize structure access\n // const SegmentedSplineParams_c9 ODT_48nits = SegmentedSplineParams_c9(\n // // coefsLow[10]\n // float[10]( -1.6989700043, -1.6989700043, -1.4779000000, -1.2291000000, -0.8648000000, -0.4480000000, 0.0051800000, 0.4511080334, 0.9113744414, 0.9113744414),\n // // coefsHigh[10]\n // float[10]( 0.5154386965, 0.8470437783, 1.1358000000, 1.3802000000, 1.5197000000, 1.5985000000, 1.6467000000, 1.6746091357, 1.6878733390, 1.6878733390 ),\n // vec2(segmented_spline_c5_fwd(0.18*pow(2.,-6.5)), 0.02), // minPoint\n // vec2(segmented_spline_c5_fwd(0.18), 4.8), // midPoint\n // vec2(segmented_spline_c5_fwd(0.18*pow(2.,6.5)), 48.0), // maxPoint\n // 0.0, // slopeLow\n // 0.04 // slopeHigh\n // );\n\n // OCES to RGB rendering space\n mediump vec3 rgbPre = AP0_2_AP1_MAT * oces;\n\n // Apply the tonescale independently in rendering-space RGB\n mediump vec3 rgbPost;\n\n // rgbPost.r = segmented_spline_c9_fwd(rgbPre.r, ODT_48nits);\n // rgbPost.g = segmented_spline_c9_fwd(rgbPre.g, ODT_48nits);\n // rgbPost.b = segmented_spline_c9_fwd(rgbPre.b, ODT_48nits);\n\n rgbPost.r = segmented_spline_c9_fwd(rgbPre.r);\n rgbPost.g = segmented_spline_c9_fwd(rgbPre.g);\n rgbPost.b = segmented_spline_c9_fwd(rgbPre.b);\n\n // Scale luminance to linear code value\n mediump vec3 linearCV = Y_2_linCV(rgbPost, CINEMA_WHITE, CINEMA_BLACK);\n\n // Apply gamma adjustment to compensate for dim surround\n linearCV = darkSurround_to_dimSurround(linearCV);\n\n // Apply desaturation to compensate for luminance difference\n linearCV = mix(vec3(dot(linearCV, AP1_RGB2Y)), linearCV, ODT_SAT_FACTOR);\n\n // Convert to display primary encoding\n // Rendering space RGB to XYZ\n mediump vec3 XYZ = AP1_2_XYZ_MAT * linearCV;\n\n // Apply CAT from ACES white point to assumed observer adapted white point\n XYZ = D60_2_D65_CAT * XYZ;\n\n // CIE XYZ to display primaries\n linearCV = XYZ_2_REC709_MAT * XYZ;\n\n // Handle out-of-gamut values\n // Clip values < 0 or > 1 (i.e. projecting outside the display primaries)\n linearCV = clamp(linearCV, vec3(0), vec3(1));\n\n // Unity already draws to a sRGB target\n return linearCV;\n}"; // eslint-disable-line
15297
-
15298
- var RRT = "#include <Tonescale>\n\n// Reference Rendering Transform (RRT)\n\n// Sigmoid function in the range 0 to 1 spanning -2 to +2.\nmediump float sigmoid_shaper(mediump float x){\n mediump float t = max(1.0 - abs(x / 2.0), 0.0);\n mediump float y = 1.0 + sign(x) * (1.0 - t * t);\n\n return y * 0.5;\n}\n\nmediump float glow_fwd(mediump float ycIn, mediump float glowGainIn, mediump float glowMid){\n mediump float glowGainOut;\n\n if (ycIn <= 2.0 / 3.0 * glowMid){\n glowGainOut = glowGainIn;\n } else if (ycIn >= 2.0 * glowMid){\n glowGainOut = 0.0;\n } else{\n glowGainOut = glowGainIn * (glowMid / ycIn - 1.0 / 2.0);\n }\n\n return glowGainOut;\n}\n\n\n// \"Glow\" module constants\nconst mediump float RRT_GLOW_GAIN = 0.05;\nconst mediump float RRT_GLOW_MID = 0.08;\n\n// Red modifier constants\nconst mediump float RRT_RED_SCALE = 0.82;\nconst mediump float RRT_RED_PIVOT = 0.03;\nconst mediump float RRT_RED_HUE = 0.0;\nconst mediump float RRT_RED_WIDTH = 135.0;\n\n// Desaturation contants\nconst mediump float RRT_SAT_FACTOR = 0.96;\n\n\n// ACES to OCES\nmediump vec3 RRT(mediump vec3 aces){\n // --- Glow module --- //\n mediump float saturation = rgb_2_saturation(aces);\n mediump float ycIn = rgb_2_yc(aces);\n mediump float s = sigmoid_shaper((saturation - 0.4) / 0.2);\n mediump float addedGlow = 1.0 + glow_fwd(ycIn, RRT_GLOW_GAIN * s, RRT_GLOW_MID);\n aces *= addedGlow;\n\n // --- Red modifier --- //\n mediump float hue = rgb_2_hue(aces);\n mediump float centeredHue = center_hue(hue, RRT_RED_HUE);\n\n mediump float hueWeight = smoothstep(0.0, 1.0, 1.0 - abs(2.0 * centeredHue / RRT_RED_WIDTH));\n hueWeight *= hueWeight;\n\n aces.r += hueWeight * saturation * (RRT_RED_PIVOT - aces.r) * (1.0 - RRT_RED_SCALE);\n\n // --- ACES to RGB rendering space --- //\n aces = clamp(aces, 0.0, HALF_MAX); // avoids saturated negative colors from becoming positive in the matrix\n mediump vec3 rgbPre = AP0_2_AP1_MAT * aces;\n rgbPre = clamp(rgbPre, 0.0, HALF_MAX);\n\n // --- Global desaturation --- //\n rgbPre = mix(vec3(dot(rgbPre, AP1_RGB2Y)), rgbPre, RRT_SAT_FACTOR);\n\n // --- Apply the tonescale independently in rendering-space RGB --- //\n mediump vec3 rgbPost;\n rgbPost.x = segmented_spline_c5_fwd(rgbPre.x);\n rgbPost.y = segmented_spline_c5_fwd(rgbPre.y);\n rgbPost.z = segmented_spline_c5_fwd(rgbPre.z);\n\n // --- RGB rendering space to OCES --- //\n mediump vec3 outputVal = AP1_2_AP0_MAT * rgbPost;\n\n return outputVal;\n}"; // eslint-disable-line
15299
-
15300
- var Tonescale = " #ifndef TONE_SCALE\n #define TONE_SCALE\n \n const mediump mat3 M = mat3(\n vec3(0.5, -1.0, 0.5),\n vec3(-1.0, 1.0, 0.5),\n vec3(0.5, 0.0, 0.0)\n );\n\n mediump float segmented_spline_c5_fwd(mediump float x){\n #ifdef GRAPHICS_API_WEBGL2\n const mediump float coefsLow[6] = float[6](-4.0000000000, -4.0000000000, -3.1573765773, -0.4852499958, 1.8477324706, 1.8477324706); // coefs for B-spline between minPoint and midPoint (units of log luminance)\n const mediump float coefsHigh[6] = float[6](-0.7185482425, 2.0810307172, 3.6681241237, 4.0000000000, 4.0000000000, 4.0000000000); // coefs for B-spline between midPoint and maxPoint (units of log luminance)\n #else\n const mediump float coefsLow_0 = -4.0000000000;\n const mediump float coefsLow_1 = -4.0000000000;\n const mediump float coefsLow_2 = -3.1573765773;\n const mediump float coefsLow_3 = -0.4852499958;\n const mediump float coefsLow_4 = 1.8477324706;\n const mediump float coefsLow_5 = 1.8477324706;\n\n const mediump float coefsHigh_0 = -0.7185482425;\n const mediump float coefsHigh_1 = 2.0810307172;\n const mediump float coefsHigh_2 = 3.6681241237;\n const mediump float coefsHigh_3 = 4.0000000000;\n const mediump float coefsHigh_4 = 4.0000000000;\n const mediump float coefsHigh_5 = 4.0000000000;\n #endif\n\n // const vec2 minPoint = vec2(0.18 * exp2(-15.0), 0.0001); // {luminance, luminance} linear extension below this\n const mediump vec2 minPoint = vec2(0.0000054931640625, 0.0001); // {luminance, luminance} linear extension below this\n const mediump vec2 midPoint = vec2(0.18, 0.48); // {luminance, luminance}\n // const vec2 maxPoint = vec2(0.18 * exp2(18.0), 10000.0); // {luminance, luminance} linear extension above this\n const mediump vec2 maxPoint = vec2(47185.92, 10000.0); // {luminance, luminance} linear extension above this\n const mediump float slopeLow = 0.0; // log-log slope of low linear extension\n const mediump float slopeHigh = 0.0; // log-log slope of high linear extension\n\n const int N_KNOTS_LOW = 4;\n const int N_KNOTS_HIGH = 4;\n\n // Check for negatives or zero before taking the log. If negative or zero,\n // set to ACESMIN.1\n mediump float logx = log10(max(x, HALF_MIN));\n mediump float logy;\n\n if (logx <= log10(minPoint.x)){\n logy = logx * slopeLow + (log10(minPoint.y) - slopeLow * log10(minPoint.x));\n } else if ((logx > log10(minPoint.x)) && (logx < log10(midPoint.x))){\n mediump float knot_coord = float(N_KNOTS_LOW - 1) * (logx - log10(minPoint.x)) / (log10(midPoint.x) - log10(minPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsLow[j], coefsLow[j + 1], coefsLow[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsLow_0, coefsLow_1, coefsLow_2);\n } else if (j == 1) {\n cf = vec3(coefsLow_1, coefsLow_2, coefsLow_3);\n } else if (j == 2) {\n cf = vec3(coefsLow_2, coefsLow_3, coefsLow_4);\n } else { // if (j == 3)\n cf = vec3(coefsLow_3, coefsLow_4, coefsLow_5);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else if ((logx >= log10(midPoint.x)) && (logx < log10(maxPoint.x))){\n mediump float knot_coord = float(N_KNOTS_HIGH - 1) * (logx - log10(midPoint.x)) / (log10(maxPoint.x) - log10(midPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsHigh[j], coefsHigh[j + 1], coefsHigh[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsHigh_0, coefsHigh_1, coefsHigh_2);\n } else if (j == 1) {\n cf = vec3(coefsHigh_1, coefsHigh_2, coefsHigh_3);\n } else if (j == 2) {\n cf = vec3(coefsHigh_2, coefsHigh_3, coefsHigh_4);\n } else { // if (j == 3)\n cf = vec3(coefsHigh_3, coefsHigh_4, coefsHigh_5);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else {\n logy = logx * slopeHigh + (log10(maxPoint.y) - slopeHigh * log10(maxPoint.x));\n }\n\n return pow(10.0, logy);\n }\n\n // The metal compiler does not optimize structure access\n // struct SegmentedSplineParams_c9{\n // float coefsLow[10]; // coefs for B-spline between minPoint and midPoint (units of log luminance)\n // float coefsHigh[10]; // coefs for B-spline between midPoint and maxPoint (units of log luminance)\n // mediump vec2 minPoint; // {luminance, luminance} linear extension below this\n // mediump vec2 midPoint; // {luminance, luminance}\n // mediump vec2 maxPoint; // {luminance, luminance} linear extension above this\n // float slopeLow; // log-log slope of low linear extension\n // float slopeHigh; // log-log slope of high linear extension\n // };\n\n\n mediump float segmented_spline_c9_fwd(mediump float x){\n // ODT_48nits\n #ifdef GRAPHICS_API_WEBGL2\n const mediump float coefsLow[10] = float[10](-1.6989700043, -1.6989700043, -1.4779000000, -1.2291000000, -0.8648000000, -0.4480000000, 0.0051800000, 0.4511080334, 0.9113744414, 0.9113744414);\n const mediump float coefsHigh[10] = float[10](0.5154386965, 0.8470437783, 1.1358000000, 1.3802000000, 1.5197000000, 1.5985000000, 1.6467000000, 1.6746091357, 1.6878733390, 1.6878733390);\n #else\n const mediump float coefsLow_0 = -1.6989700043;\n const mediump float coefsLow_1 = -1.6989700043;\n const mediump float coefsLow_2 = -1.4779000000;\n const mediump float coefsLow_3 = -1.2291000000;\n const mediump float coefsLow_4 = -0.8648000000;\n const mediump float coefsLow_5 = -0.4480000000;\n const mediump float coefsLow_6 = 0.0051800000;\n const mediump float coefsLow_7 = 0.4511080334;\n const mediump float coefsLow_8 = 0.9113744414;\n const mediump float coefsLow_9 = 0.9113744414;\n\n const mediump float coefsHigh_0 = 0.5154386965;\n const mediump float coefsHigh_1 = 0.8470437783;\n const mediump float coefsHigh_2 = 1.1358000000;\n const mediump float coefsHigh_3 = 1.3802000000;\n const mediump float coefsHigh_4 = 1.5197000000;\n const mediump float coefsHigh_5 = 1.5985000000;\n const mediump float coefsHigh_6 = 1.6467000000;\n const mediump float coefsHigh_7 = 1.6746091357;\n const mediump float coefsHigh_8 = 1.6878733390;\n const mediump float coefsHigh_9 = 1.6878733390;\n #endif\n\n // mediump vec2 minPoint = vec2(segmented_spline_c5_fwd(0.18 * pow(2.0, -6.5)), 0.02);\n // mediump vec2 midPoint = vec2(segmented_spline_c5_fwd(0.18), 4.8);\n // mediump vec2 maxPoint = vec2(segmented_spline_c5_fwd(0.18 * pow(2., 6.5)), 48.0);\n\n const mediump vec2 minPoint = vec2(0.0028799, 0.02);\n const mediump vec2 midPoint = vec2(4.799999, 4.8);\n const mediump vec2 maxPoint = vec2(1005.719, 48.0);\n\n const mediump float slopeLow = 0.0;\n const mediump float slopeHigh = 0.04;\n\n const int N_KNOTS_LOW = 8;\n const int N_KNOTS_HIGH = 8;\n\n // Check for negatives or zero before taking the log. If negative or zero,\n // set to OCESMIN.\n mediump float logx = log10(max(x, 1e-4));\n mediump float logy;\n\n if (logx <= log10(minPoint.x)) {\n logy = logx * slopeLow + (log10(minPoint.y) - slopeLow * log10(minPoint.x));\n } else if ((logx > log10(minPoint.x)) && (logx < log10(midPoint.x))) {\n mediump float knot_coord = float(N_KNOTS_LOW - 1) * (logx - log10(minPoint.x)) / (log10(midPoint.x) - log10(minPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsLow[j], coefsLow[j + 1], coefsLow[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsLow_0, coefsLow_1, coefsLow_2);\n } else if (j == 1) {\n cf = vec3(coefsLow_1, coefsLow_2, coefsLow_3);\n } else if (j == 2) {\n cf = vec3(coefsLow_2, coefsLow_3, coefsLow_4);\n } else if (j == 3) {\n cf = vec3(coefsLow_3, coefsLow_4, coefsLow_5);\n } else if (j == 4) {\n cf = vec3(coefsLow_4, coefsLow_5, coefsLow_6);\n } else if (j == 5) {\n cf = vec3(coefsLow_5, coefsLow_6, coefsLow_7);\n } else if (j == 6) {\n cf = vec3(coefsLow_6, coefsLow_7, coefsLow_8);\n } else { // if (j == 7)\n cf = vec3(coefsLow_7, coefsLow_8, coefsLow_9);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else if ((logx >= log10(midPoint.x)) && (logx < log10(maxPoint.x))) {\n mediump float knot_coord = float(N_KNOTS_HIGH - 1) * (logx - log10(midPoint.x)) / (log10(maxPoint.x) - log10(midPoint.x));\n int j = int(knot_coord);\n mediump float t = knot_coord - float(j);\n\n mediump vec3 cf;\n #ifdef GRAPHICS_API_WEBGL2\n cf = vec3(coefsHigh[j], coefsHigh[j + 1], coefsHigh[j + 2]);\n #else\n if (j <= 0) {\n cf = vec3(coefsHigh_0, coefsHigh_1, coefsHigh_2);\n } else if (j == 1) {\n cf = vec3(coefsHigh_1, coefsHigh_2, coefsHigh_3);\n } else if (j == 2) {\n cf = vec3(coefsHigh_2, coefsHigh_3, coefsHigh_4);\n } else if (j == 3) {\n cf = vec3(coefsHigh_3, coefsHigh_4, coefsHigh_5);\n } else if (j == 4) {\n cf = vec3(coefsHigh_4, coefsHigh_5, coefsHigh_6);\n } else if (j == 5) {\n cf = vec3(coefsHigh_5, coefsHigh_6, coefsHigh_7);\n } else if (j == 6) {\n cf = vec3(coefsHigh_6, coefsHigh_7, coefsHigh_8);\n } else { // if (j == 7)\n cf = vec3(coefsHigh_7, coefsHigh_8, coefsHigh_9);\n }\n #endif\n\n mediump vec3 monomials = vec3(t * t, t, 1.0);\n logy = dot(monomials, M * cf);\n } else {\n logy = logx * slopeHigh + (log10(maxPoint.y) - slopeHigh * log10(maxPoint.x));\n }\n\n return pow(10.0, logy);\n }\n\n\n#endif"; // eslint-disable-line
15301
-
15302
- var NeutralTonemapping = "// Neutral tonemapping (Hable/Hejl/Frostbite)\n// Input is linear RGB\n// More accuracy to avoid NaN on extremely high values.\nvec3 neutralCurve(vec3 x, float a, float b, float c, float d, float e, float f){\n return vec3(((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f);\n}\n\n#define TONEMAPPING_CLAMP_MAX 435.18712 //(-b + sqrt(b * b - 4 * a * (HALF_MAX - d * f))) / (2 * a * whiteScale)\n//Extremely high values cause NaN output when using fp16, we clamp to avoid the performace hit of switching to fp32\n//The overflow happens in (x * (a * x + b) + d * f) of the NeutralCurve, highest value that avoids fp16 precision errors is ~571.56873\n//Since whiteScale is constant (~1.31338) max input is ~435.18712\n\nvec3 neutralTonemap(vec3 color){\n const float a = 0.2;\n const float b = 0.29;\n const float c = 0.24;\n const float d = 0.272;\n const float e = 0.02;\n const float f = 0.3;\n // const float whiteLevel = 5.3;\n // const float whiteClip = 1.0;\n\n #ifndef GL_FRAGMENT_PRECISION_HIGH\n color = min(color, TONEMAPPING_CLAMP_MAX);\n #endif\n\n // 1.0 / neutralCurve(whiteLevel, a, b, c, d, e, f);\n const float whiteScale = 1.31338; \n color = neutralCurve(color * whiteScale, a, b, c, d, e, f);\n color *= whiteScale;\n\n // Post-curve white point adjustment\n // color /= whiteClip;\n\n return color;\n}"; // eslint-disable-line
15303
-
15304
- var UberPost = "#include <PostCommon>\n#include <Filtering>\n#include <NeutralTonemapping>\n#include <ACESTonemapping>\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n#ifdef ENABLE_EFFECT_BLOOM\n\tuniform sampler2D material_BloomTexture;\n\tuniform sampler2D material_BloomDirtTexture;\n\tuniform vec4 material_BloomTint;\n\tuniform vec4 material_BloomDirtTilingOffset;\n\tuniform vec4 material_BloomIntensityParams; // x: bloom intensity, y: dirt intensity\n#endif\n\n\nvoid main(){\n\tmediump vec4 color = texture2DSRGB(renderer_BlitTexture, v_uv);\n\n\t#ifdef ENABLE_EFFECT_BLOOM\n \t#ifdef BLOOM_HQ\n \t mediump vec4 bloom = sampleTexture2DBicubic(material_BloomTexture, v_uv, renderer_texelSize);\n \t#else\n \t mediump vec4 bloom = texture2DSRGB(material_BloomTexture, v_uv);\n \t#endif\n\n \tbloom *= material_BloomIntensityParams.x;\n \tcolor += bloom * material_BloomTint;\n\n \t#ifdef BLOOM_DIRT\n \t mediump vec4 dirt = texture2DSRGB(material_BloomDirtTexture, v_uv * material_BloomDirtTilingOffset.xy + material_BloomDirtTilingOffset.zw);\n \t dirt *= material_BloomIntensityParams.y;\n \t // Additive bloom (artist friendly)\n \t color += dirt * bloom;\n \t#endif\n\t#endif\n\n\t#ifdef ENABLE_EFFECT_TONEMAPPING\n\t\t#if TONEMAPPING_MODE == 0\n \t\tcolor.rgb = neutralTonemap(color.rgb);\n \t#elif TONEMAPPING_MODE == 1\n \t\tcolor.rgb = ACESTonemap(color.rgb);\n \t#endif\n\n \tcolor.rgb = clamp(color.rgb, vec3(0), vec3(1));\n\t#endif\n\n gl_FragColor = color;\n}"; // eslint-disable-line
15305
-
15306
14946
  var PostProcessUberPass = /*#__PURE__*/ function(PostProcessPass) {
15307
14947
  _inherits(PostProcessUberPass, PostProcessPass);
15308
14948
  function PostProcessUberPass(engine) {
@@ -15311,15 +14951,9 @@ var PostProcessUberPass = /*#__PURE__*/ function(PostProcessPass) {
15311
14951
  _this.event = PostProcessPassEvent.AfterUber - 1;
15312
14952
  // Uber Material
15313
14953
  var uberMaterial = new Material(engine, Shader.find(PostProcessUberPass.UBER_SHADER_NAME));
15314
- var uberDepthState = uberMaterial.renderState.depthState;
15315
- uberDepthState.enabled = false;
15316
- uberDepthState.writeEnabled = false;
15317
14954
  _this._uberMaterial = uberMaterial;
15318
14955
  // Bloom Material
15319
14956
  var bloomMaterial = new Material(engine, Shader.find(BloomEffect.SHADER_NAME));
15320
- var bloomDepthState = bloomMaterial.renderState.depthState;
15321
- bloomDepthState.enabled = false;
15322
- bloomDepthState.writeEnabled = false;
15323
14957
  _this._bloomMaterial = bloomMaterial;
15324
14958
  // ShaderData initialization
15325
14959
  var bloomShaderData = bloomMaterial.shaderData;
@@ -15477,24 +15111,7 @@ var PostProcessUberPass = /*#__PURE__*/ function(PostProcessPass) {
15477
15111
  };
15478
15112
  return PostProcessUberPass;
15479
15113
  }(PostProcessPass);
15480
- PostProcessUberPass.UBER_SHADER_NAME = "UberPost";
15481
- Object.assign(ShaderLib, {
15482
- PostCommon: PostCommon,
15483
- Filtering: Filtering,
15484
- ODT: ODT,
15485
- RRT: RRT,
15486
- Tonescale: Tonescale,
15487
- ColorTransform: ColorTransform,
15488
- NeutralTonemapping: NeutralTonemapping,
15489
- ACESTonemapping: ACESTonemapping
15490
- });
15491
- Shader.create(PostProcessUberPass.UBER_SHADER_NAME, blitVs, UberPost);
15492
-
15493
- var FinalAntiAliasingFS = "#define FXAA_PC 1\n#define FXAA_QUALITY_PRESET 12\n#define FXAA_GREEN_AS_LUMA 0\n#if defined(GRAPHICS_API_WEBGL2)\n #define FXAA_GLSL_130 1\n#elif defined(GRAPHICS_API_WEBGL1)\n #define FXAA_GLSL_120 1\n#endif\n\n#include <common>\n#include <FXAA3_11>\n\nconst FxaaFloat FXAA_SUBPIXEL_BLEND_AMOUNT = 0.75;\nconst FxaaFloat FXAA_RELATIVE_CONTRAST_THRESHOLD = 0.166;\nconst FxaaFloat FXAA_ABSOLUTE_CONTRAST_THRESHOLD = 0.0833;\n\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\nuniform vec4 renderer_texelSize; // x: 1/width, y: 1/height, z: width, w: height\n\nvec4 applyFXAA(vec4 color, vec2 positionNDC, vec4 sourceSize, sampler2D blitTexture)\n{\n return FxaaPixelShader(\n positionNDC,\n color,\n blitTexture,\n sourceSize.xy,\n FXAA_SUBPIXEL_BLEND_AMOUNT,\n FXAA_RELATIVE_CONTRAST_THRESHOLD,\n FXAA_ABSOLUTE_CONTRAST_THRESHOLD\n );\n}\n\nvoid main(){\n\tmediump vec4 color = texture2D(renderer_BlitTexture, v_uv);\n\n color = applyFXAA(color, v_uv, renderer_texelSize, renderer_BlitTexture);\n\n // We have convert the color to sRGB space in sRGB pass\n // So we need to convert it back to linear space when output to render target.\n #ifndef ENGINE_OUTPUT_SRGB_CORRECT\n color.rgb /= color.a;\n color = sRGBToLinear(color);\n color.rgb *= color.a;\n #endif\n\n gl_FragColor = color;\n}"; // eslint-disable-line
15494
-
15495
- var SRGBFS = "#include <common>\nvarying vec2 v_uv;\nuniform sampler2D renderer_BlitTexture;\n\nvoid main(){\n\tmediump vec4 color = texture2DSRGB(renderer_BlitTexture, v_uv);\n\n // This is final output, maybe has alpha\n // 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\n // But the actual transparent canvas can be composited with any color of the browser background\n\n // So we assume non-transparent SRGB conversion. Then use the Alpha value and the background canvas to do SRGB blending \n // Although it is non-linear blending, it is more scientific\n color.rgb = color.rgb / color.a;\n color = linearToSRGB(color);\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"; // eslint-disable-line
15496
-
15497
- var FXAA3_11 = "//----------------------------------------------------------------------------------\n// This file was obatined from: https://github.com/hghdev/NVIDIAGameWorks-GraphicsSamples/blob/master/samples/es3-kepler/FXAA/FXAA3_11.h\n// NVIDIA paper: https://www.iryoku.com/aacourse/downloads/09-FXAA-3.11-in-15-Slides.pdf\n// Modifications to this file done by Galacean:\n// * Deleted HLSL-related macros\n// * Deleted the macros and function except for 'FXAA_PC == 1' \n// * Deleted the useless parameters in 'FxaaPixelShader' \n// * Webgl does not compile the double underline, so we remove the double underline for macros\n// * Changed the 'FXAA_GREEN_AS_LUMA == 0' code-path to compute luminance since we don't precompute luminance into the alpha channel\n// * Change the alpha value of the `ret` finally returned by the function from brightness to transparency when `FXAA_DISCARD == 1` code path\n//----------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------\n// File: es3-kepler\\FXAA/FXAA3_11.h\n// SDK Version: v3.00\n// Email: gameworks@nvidia.com\n// Site: http://developer.nvidia.com/\n//\n// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// * Neither the name of NVIDIA CORPORATION nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//----------------------------------------------------------------------------------\n/*============================================================================\n\n\n NVIDIA FXAA 3.11 by TIMOTHY LOTTES\n\n------------------------------------------------------------------------------\n INTEGRATION CHECKLIST\n------------------------------------------------------------------------------\n(1.)\nIn the shader source, setup defines for the desired configuration.\nWhen providing multiple shaders (for different presets),\nsimply setup the defines differently in multiple files.\nExample,\n\n #define FXAA_PC 1\n #define FXAA_HLSL_5 1\n #define FXAA_QUALITY_PRESET 12\n\nOr,\n\n #define FXAA_360 1\n\nOr,\n\n #define FXAA_PS3 1\n\nEtc.\n\n(2.)\nThen include this file,\n\n #include \"Fxaa3_11.h\"\n\n(3.)\nThen call the FXAA pixel shader from within your desired shader.\nLook at the FXAA Quality FxaaPixelShader() for docs on inputs.\nAs for FXAA 3.11 all inputs for all shaders are the same\nto enable easy porting between platforms.\n\n return FxaaPixelShader(...);\n\n(4.)\nInsure pass prior to FXAA outputs RGBL (see next section).\nOr use,\n\n #define FXAA_GREEN_AS_LUMA 1\n\n(5.)\nSetup engine to provide the following constants\nwhich are used in the FxaaPixelShader() inputs,\n\n FxaaFloat2 fxaaQualityRcpFrame,\n FxaaFloat4 fxaaConsoleRcpFrameOpt,\n FxaaFloat4 fxaaConsoleRcpFrameOpt2,\n FxaaFloat4 fxaaConsole360RcpFrameOpt2,\n FxaaFloat fxaaQualitySubpix,\n FxaaFloat fxaaQualityEdgeThreshold,\n FxaaFloat fxaaQualityEdgeThresholdMin,\n FxaaFloat fxaaConsoleEdgeSharpness,\n FxaaFloat fxaaConsoleEdgeThreshold,\n FxaaFloat fxaaConsoleEdgeThresholdMin,\n FxaaFloat4 fxaaConsole360ConstDir\n\nLook at the FXAA Quality FxaaPixelShader() for docs on inputs.\n\n(6.)\nHave FXAA vertex shader run as a full screen triangle,\nand output \"pos\" and \"fxaaConsolePosPos\"\nsuch that inputs in the pixel shader provide,\n\n // {xy} = center of pixel\n FxaaFloat2 pos,\n\n // {xy_} = upper left of pixel\n // {_zw} = lower right of pixel\n FxaaFloat4 fxaaConsolePosPos,\n\n(7.)\nInsure the texture sampler(s) used by FXAA are set to bilinear filtering.\n\n\n------------------------------------------------------------------------------\n INTEGRATION - RGBL AND COLORSPACE\n------------------------------------------------------------------------------\nFXAA3 requires RGBL as input unless the following is set,\n\n #define FXAA_GREEN_AS_LUMA 1\n\nIn which case the engine uses green in place of luma,\nand requires RGB input is in a non-linear colorspace.\n\nRGB should be LDR (low dynamic range).\nSpecifically do FXAA after tonemapping.\n\nRGB data as returned by a texture fetch can be non-linear,\nor linear when FXAA_GREEN_AS_LUMA is not set.\nNote an \"sRGB format\" texture counts as linear,\nbecause the result of a texture fetch is linear data.\nRegular \"RGBA8\" textures in the sRGB colorspace are non-linear.\n\nIf FXAA_GREEN_AS_LUMA is not set,\nluma must be stored in the alpha channel prior to running FXAA.\nThis luma should be in a perceptual space (could be gamma 2.0).\nExample pass before FXAA where output is gamma 2.0 encoded,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n color.rgb = sqrt(color.rgb); // gamma 2.0 color output\n return color;\n\nTo use FXAA,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n color.rgb = sqrt(color.rgb); // gamma 2.0 color output\n color.a = dot(color.rgb, FxaaFloat3(0.299, 0.587, 0.114)); // compute luma\n return color;\n\nAnother example where output is linear encoded,\nsay for instance writing to an sRGB formated render target,\nwhere the render target does the conversion back to sRGB after blending,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n return color;\n\nTo use FXAA,\n\n color.rgb = ToneMap(color.rgb); // linear color output\n color.a = sqrt(dot(color.rgb, FxaaFloat3(0.299, 0.587, 0.114))); // compute luma\n return color;\n\nGetting luma correct is required for the algorithm to work correctly.\n\n\n------------------------------------------------------------------------------\n BEING LINEARLY CORRECT?\n------------------------------------------------------------------------------\nApplying FXAA to a framebuffer with linear RGB color will look worse.\nThis is very counter intuitive, but happends to be true in this case.\nThe reason is because dithering artifacts will be more visiable\nin a linear colorspace.\n\n\n------------------------------------------------------------------------------\n COMPLEX INTEGRATION\n------------------------------------------------------------------------------\nQ. What if the engine is blending into RGB before wanting to run FXAA?\n\nA. In the last opaque pass prior to FXAA,\n have the pass write out luma into alpha.\n Then blend into RGB only.\n FXAA should be able to run ok\n assuming the blending pass did not any add aliasing.\n This should be the common case for particles and common blending passes.\n\nA. Or use FXAA_GREEN_AS_LUMA.\n\n============================================================================*/\n\n/*============================================================================\n\n INTEGRATION KNOBS\n\n============================================================================*/\n/*==========================================================================*/\n#ifndef FXAA_PC\n //\n // FXAA Quality\n // The high quality PC algorithm.\n //\n #define FXAA_PC 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_GLSL_120\n #define FXAA_GLSL_120 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_GLSL_130\n #define FXAA_GLSL_130 0\n#endif\n/*--------------------------------------------------------------------------*/\n/*==========================================================================*/\n#ifndef FXAA_GREEN_AS_LUMA\n //\n // For those using non-linear color,\n // and either not able to get luma in alpha, or not wanting to,\n // this enables FXAA to run using green as a proxy for luma.\n // So with this enabled, no need to pack luma in alpha.\n //\n // This will turn off AA on anything which lacks some amount of green.\n // Pure red and blue or combination of only R and B, will get no AA.\n //\n // Might want to lower the settings for both,\n // fxaaConsoleEdgeThresholdMin\n // fxaaQualityEdgeThresholdMin\n // In order to insure AA does not get turned off on colors \n // which contain a minor amount of green.\n //\n // 1 = On.\n // 0 = Off.\n //\n #define FXAA_GREEN_AS_LUMA 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_EARLY_EXIT\n //\n // Controls algorithm's early exit path.\n // On PS3 turning this ON adds 2 cycles to the shader.\n // On 360 turning this OFF adds 10ths of a millisecond to the shader.\n // Turning this off on console will result in a more blurry image.\n // So this defaults to on.\n //\n // 1 = On.\n // 0 = Off.\n //\n #define FXAA_EARLY_EXIT 1\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_DISCARD\n //\n // Only valid for PC OpenGL currently.\n // Probably will not work when FXAA_GREEN_AS_LUMA = 1.\n //\n // 1 = Use discard on pixels which don't need AA.\n // For APIs which enable concurrent TEX+ROP from same surface.\n // 0 = Return unchanged color on pixels which don't need AA.\n //\n #define FXAA_DISCARD 0\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_FAST_PIXEL_OFFSET\n //\n // Used for GLSL 120 only.\n //\n // 1 = GL API supports fast pixel offsets\n // 0 = do not use fast pixel offsets\n //\n #ifdef GL_EXT_gpu_shader4\n #define FXAA_FAST_PIXEL_OFFSET 1\n #endif\n #ifdef GL_NV_gpu_shader5\n #define FXAA_FAST_PIXEL_OFFSET 1\n #endif\n #ifdef gpu_shader5\n #define FXAA_FAST_PIXEL_OFFSET 1\n #endif\n #ifndef FXAA_FAST_PIXEL_OFFSET\n #define FXAA_FAST_PIXEL_OFFSET 0\n #endif\n#endif\n/*--------------------------------------------------------------------------*/\n#ifndef FXAA_GATHER4_ALPHA\n //\n // 1 = API supports gather4 on alpha channel.\n // 0 = API does not support gather4 on alpha channel.\n //\n #ifdef gpu_shader5\n #define FXAA_GATHER4_ALPHA 1\n #endif\n #ifdef GL_NV_gpu_shader5\n #define FXAA_GATHER4_ALPHA 1\n #endif\n #ifndef FXAA_GATHER4_ALPHA\n #define FXAA_GATHER4_ALPHA 0\n #endif\n#endif\n\n/*============================================================================\n FXAA QUALITY - TUNING KNOBS\n------------------------------------------------------------------------------\nNOTE the other tuning knobs are now in the shader function inputs!\n============================================================================*/\n#ifndef FXAA_QUALITY_PRESET\n //\n // Choose the quality preset.\n // This needs to be compiled into the shader as it affects code.\n // Best option to include multiple presets is to \n // in each shader define the preset, then include this file.\n // \n // OPTIONS\n // -----------------------------------------------------------------------\n // 10 to 15 - default medium dither (10=fastest, 15=highest quality)\n // 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality)\n // 39 - no dither, very expensive \n //\n // NOTES\n // -----------------------------------------------------------------------\n // 12 = slightly faster then FXAA 3.9 and higher edge quality (default)\n // 13 = about same speed as FXAA 3.9 and better than 12\n // 23 = closest to FXAA 3.9 visually and performance wise\n // _ = the lowest digit is directly related to performance\n // _ = the highest digit is directly related to style\n // \n #define FXAA_QUALITY_PRESET 12\n#endif\n\n/*============================================================================\n\n FXAA QUALITY - PRESETS\n\n============================================================================*/\n\n/*============================================================================\n FXAA QUALITY - MEDIUM DITHER PRESETS\n============================================================================*/\n#if (FXAA_QUALITY_PRESET == 10)\n #define FXAA_QUALITY_PS 3\n #define FXAA_QUALITY_P0 1.5\n #define FXAA_QUALITY_P1 3.0\n #define FXAA_QUALITY_P2 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 11)\n #define FXAA_QUALITY_PS 4\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 3.0\n #define FXAA_QUALITY_P3 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 12)\n #define FXAA_QUALITY_PS 5\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 4.0\n #define FXAA_QUALITY_P4 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 13)\n #define FXAA_QUALITY_PS 6\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 4.0\n #define FXAA_QUALITY_P5 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 14)\n #define FXAA_QUALITY_PS 7\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 4.0\n #define FXAA_QUALITY_P6 12.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 15)\n #define FXAA_QUALITY_PS 8\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 4.0\n #define FXAA_QUALITY_P7 12.0\n#endif\n\n/*============================================================================\n FXAA QUALITY - LOW DITHER PRESETS\n============================================================================*/\n#if (FXAA_QUALITY_PRESET == 20)\n #define FXAA_QUALITY_PS 3\n #define FXAA_QUALITY_P0 1.5\n #define FXAA_QUALITY_P1 2.0\n #define FXAA_QUALITY_P2 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 21)\n #define FXAA_QUALITY_PS 4\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 22)\n #define FXAA_QUALITY_PS 5\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 23)\n #define FXAA_QUALITY_PS 6\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 24)\n #define FXAA_QUALITY_PS 7\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 3.0\n #define FXAA_QUALITY_P6 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 25)\n #define FXAA_QUALITY_PS 8\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 4.0\n #define FXAA_QUALITY_P7 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 26)\n #define FXAA_QUALITY_PS 9\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 4.0\n #define FXAA_QUALITY_P8 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 27)\n #define FXAA_QUALITY_PS 10\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 4.0\n #define FXAA_QUALITY_P9 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 28)\n #define FXAA_QUALITY_PS 11\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 2.0\n #define FXAA_QUALITY_P9 4.0\n #define FXAA_QUALITY_P10 8.0\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_QUALITY_PRESET == 29)\n #define FXAA_QUALITY_PS 12\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.5\n #define FXAA_QUALITY_P2 2.0\n #define FXAA_QUALITY_P3 2.0\n #define FXAA_QUALITY_P4 2.0\n #define FXAA_QUALITY_P5 2.0\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 2.0\n #define FXAA_QUALITY_P9 2.0\n #define FXAA_QUALITY_P10 4.0\n #define FXAA_QUALITY_P11 8.0\n#endif\n\n/*============================================================================\n FXAA QUALITY - EXTREME QUALITY\n============================================================================*/\n#if (FXAA_QUALITY_PRESET == 39)\n #define FXAA_QUALITY_PS 12\n #define FXAA_QUALITY_P0 1.0\n #define FXAA_QUALITY_P1 1.0\n #define FXAA_QUALITY_P2 1.0\n #define FXAA_QUALITY_P3 1.0\n #define FXAA_QUALITY_P4 1.0\n #define FXAA_QUALITY_P5 1.5\n #define FXAA_QUALITY_P6 2.0\n #define FXAA_QUALITY_P7 2.0\n #define FXAA_QUALITY_P8 2.0\n #define FXAA_QUALITY_P9 2.0\n #define FXAA_QUALITY_P10 4.0\n #define FXAA_QUALITY_P11 8.0\n#endif\n\n\n/*============================================================================\n\n API PORTING\n\n============================================================================*/\n#if (FXAA_GLSL_120 == 1) || (FXAA_GLSL_130 == 1)\n #define FxaaBool bool\n #define FxaaDiscard discard\n #define FxaaFloat float\n #define FxaaFloat2 vec2\n #define FxaaFloat3 vec3\n #define FxaaFloat4 vec4\n #define FxaaHalf float\n #define FxaaHalf2 vec2\n #define FxaaHalf3 vec3\n #define FxaaHalf4 vec4\n #define FxaaInt2 ivec2\n #define FxaaSat(x) clamp(x, 0.0, 1.0)\n #define FxaaTex sampler2D\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_GLSL_120 == 1)\n // Requires,\n // #version 120\n // And at least,\n // #extension GL_EXT_gpu_shader4 : enable\n // (or set FXAA_FAST_PIXEL_OFFSET 1 to work like DX9)\n #define FxaaTexTop(t, p) texture2DLodEXT(t, p, 0.0)\n #if (FXAA_FAST_PIXEL_OFFSET == 1)\n #define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o)\n #else\n #define FxaaTexOff(t, p, o, r) texture2DLodEXT(t, p + (o * r), 0.0)\n #endif\n #if (FXAA_GATHER4_ALPHA == 1)\n // use #extension gpu_shader5 : enable\n #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)\n #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)\n #define FxaaTexGreen4(t, p) textureGather(t, p, 1)\n #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)\n #endif\n#endif\n/*--------------------------------------------------------------------------*/\n#if (FXAA_GLSL_130 == 1)\n // Requires \"#version 130\" or better\n #define FxaaTexTop(t, p) textureLod(t, p, 0.0)\n #define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o)\n #if (FXAA_GATHER4_ALPHA == 1)\n // use #extension gpu_shader5 : enable\n #define FxaaTexAlpha4(t, p) textureGather(t, p, 3)\n #define FxaaTexOffAlpha4(t, p, o) textureGatherOffset(t, p, o, 3)\n #define FxaaTexGreen4(t, p) textureGather(t, p, 1)\n #define FxaaTexOffGreen4(t, p, o) textureGatherOffset(t, p, o, 1)\n #endif\n#endif\n/*--------------------------------------------------------------------------*/\n\n\n/*============================================================================\n GREEN AS LUMA OPTION SUPPORT FUNCTION\n============================================================================*/\n#if (FXAA_GREEN_AS_LUMA == 0)\n FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return dot(rgba.xyz, FxaaFloat3(0.299, 0.587, 0.114));}\n#else\n FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; }\n#endif \n\n\n/*============================================================================\n\n FXAA3 QUALITY - PC\n\n============================================================================*/\n#if (FXAA_PC == 1)\n/*--------------------------------------------------------------------------*/\nFxaaFloat4 FxaaPixelShader(\n // Use noperspective interpolation here (turn off perspective interpolation).\n // {xy} = center of pixel\n FxaaFloat2 pos,\n //\n // Reuse the center sample as it's already available\n // {rgb_} = the color of the center pixel (alpha won't be used)\n FxaaFloat4 rgbyM,\n //\n // Input color texture.\n // {rgb_} = color in linear or perceptual color space\n // if (FXAA_GREEN_AS_LUMA == 0)\n // {__a} = luma in perceptual color space (not linear)\n FxaaTex tex,\n //\n // Only used on FXAA Quality.\n // This must be from a constant/uniform.\n // {x_} = 1.0/screenWidthInPixels\n // {_y} = 1.0/screenHeightInPixels\n FxaaFloat2 fxaaQualityRcpFrame,\n //\n // Only used on FXAA Quality.\n // This used to be the FXAA_QUALITY_SUBPIX define.\n // It is here now to allow easier tuning.\n // Choose the amount of sub-pixel aliasing removal.\n // This can effect sharpness.\n // 1.00 - upper limit (softer)\n // 0.75 - default amount of filtering\n // 0.50 - lower limit (sharper, less sub-pixel aliasing removal)\n // 0.25 - almost off\n // 0.00 - completely off\n FxaaFloat fxaaQualitySubpix,\n //\n // Only used on FXAA Quality.\n // This used to be the FXAA_QUALITY_EDGE_THRESHOLD define.\n // It is here now to allow easier tuning.\n // The minimum amount of local contrast required to apply algorithm.\n // 0.333 - too little (faster)\n // 0.250 - low quality\n // 0.166 - default\n // 0.125 - high quality\n // 0.063 - overkill (slower)\n FxaaFloat fxaaQualityEdgeThreshold,\n //\n // Only used on FXAA Quality.\n // This used to be the FXAA_QUALITY_EDGE_THRESHOLD_MIN define.\n // It is here now to allow easier tuning.\n // Trims the algorithm from processing darks.\n // 0.0833 - upper limit (default, the start of visible unfiltered edges)\n // 0.0625 - high quality (faster)\n // 0.0312 - visible limit (slower)\n // Special notes when using FXAA_GREEN_AS_LUMA,\n // Likely want to set this to zero.\n // As colors that are mostly not-green\n // will appear very dark in the green channel!\n // Tune by looking at mostly non-green content,\n // then start at zero and increase until aliasing is a problem.\n FxaaFloat fxaaQualityEdgeThresholdMin\n) {\n/*--------------------------------------------------------------------------*/\n FxaaFloat2 posM;\n posM.x = pos.x;\n posM.y = pos.y;\n #if (FXAA_GATHER4_ALPHA == 1)\n #if (FXAA_DISCARD == 0)\n FxaaFloat lumaM = FxaaLuma(rgbyM);\n #endif\n #if (FXAA_GREEN_AS_LUMA == 0)\n FxaaFloat4 luma4A = FxaaTexAlpha4(tex, posM);\n FxaaFloat4 luma4B = FxaaTexOffAlpha4(tex, posM, FxaaInt2(-1, -1));\n #else\n FxaaFloat4 luma4A = FxaaTexGreen4(tex, posM);\n FxaaFloat4 luma4B = FxaaTexOffGreen4(tex, posM, FxaaInt2(-1, -1));\n #endif\n #if (FXAA_DISCARD == 1)\n FxaaFloat lumaM = luma4A.w;\n #endif\n #define lumaE luma4A.z\n #define lumaS luma4A.x\n #define lumaSE luma4A.y\n #define lumaNW luma4B.w\n #define lumaN luma4B.z\n #define lumaW luma4B.x\n #else\n FxaaFloat lumaM = FxaaLuma(rgbyM);\n FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy));\n #endif\n/*--------------------------------------------------------------------------*/\n FxaaFloat maxSM = max(lumaS, lumaM);\n FxaaFloat minSM = min(lumaS, lumaM);\n FxaaFloat maxESM = max(lumaE, maxSM);\n FxaaFloat minESM = min(lumaE, minSM);\n FxaaFloat maxWN = max(lumaN, lumaW);\n FxaaFloat minWN = min(lumaN, lumaW);\n FxaaFloat rangeMax = max(maxWN, maxESM);\n FxaaFloat rangeMin = min(minWN, minESM);\n FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold;\n FxaaFloat range = rangeMax - rangeMin;\n FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled);\n FxaaBool earlyExit = range < rangeMaxClamped;\n/*--------------------------------------------------------------------------*/\n if(earlyExit)\n #if (FXAA_DISCARD == 1)\n FxaaDiscard;\n #else\n return rgbyM;\n #endif\n/*--------------------------------------------------------------------------*/\n #if (FXAA_GATHER4_ALPHA == 0)\n FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));\n #else\n FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(1, -1), fxaaQualityRcpFrame.xy));\n FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));\n #endif\n/*--------------------------------------------------------------------------*/\n FxaaFloat lumaNS = lumaN + lumaS;\n FxaaFloat lumaWE = lumaW + lumaE;\n FxaaFloat subpixRcpRange = 1.0/range;\n FxaaFloat subpixNSWE = lumaNS + lumaWE;\n FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS;\n FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE;\n/*--------------------------------------------------------------------------*/\n FxaaFloat lumaNESE = lumaNE + lumaSE;\n FxaaFloat lumaNWNE = lumaNW + lumaNE;\n FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE;\n FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE;\n/*--------------------------------------------------------------------------*/\n FxaaFloat lumaNWSW = lumaNW + lumaSW;\n FxaaFloat lumaSWSE = lumaSW + lumaSE;\n FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2);\n FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2);\n FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW;\n FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE;\n FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4;\n FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4;\n/*--------------------------------------------------------------------------*/\n FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE;\n FxaaFloat lengthSign = fxaaQualityRcpFrame.x;\n FxaaBool horzSpan = edgeHorz >= edgeVert;\n FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE;\n/*--------------------------------------------------------------------------*/\n if(!horzSpan) lumaN = lumaW;\n if(!horzSpan) lumaS = lumaE;\n if(horzSpan) lengthSign = fxaaQualityRcpFrame.y;\n FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM;\n/*--------------------------------------------------------------------------*/\n FxaaFloat gradientN = lumaN - lumaM;\n FxaaFloat gradientS = lumaS - lumaM;\n FxaaFloat lumaNN = lumaN + lumaM;\n FxaaFloat lumaSS = lumaS + lumaM;\n FxaaBool pairN = abs(gradientN) >= abs(gradientS);\n FxaaFloat gradient = max(abs(gradientN), abs(gradientS));\n if(pairN) lengthSign = -lengthSign;\n FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange);\n/*--------------------------------------------------------------------------*/\n FxaaFloat2 posB;\n posB.x = posM.x;\n posB.y = posM.y;\n FxaaFloat2 offNP;\n offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;\n offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;\n if(!horzSpan) posB.x += lengthSign * 0.5;\n if( horzSpan) posB.y += lengthSign * 0.5;\n/*--------------------------------------------------------------------------*/\n FxaaFloat2 posN;\n posN.x = posB.x - offNP.x * FXAA_QUALITY_P0;\n posN.y = posB.y - offNP.y * FXAA_QUALITY_P0;\n FxaaFloat2 posP;\n posP.x = posB.x + offNP.x * FXAA_QUALITY_P0;\n posP.y = posB.y + offNP.y * FXAA_QUALITY_P0;\n FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0;\n FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN));\n FxaaFloat subpixE = subpixC * subpixC;\n FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP));\n/*--------------------------------------------------------------------------*/\n if(!pairN) lumaNN = lumaSS;\n FxaaFloat gradientScaled = gradient * 1.0/4.0;\n FxaaFloat lumaMM = lumaM - lumaNN * 0.5;\n FxaaFloat subpixF = subpixD * subpixE;\n FxaaBool lumaMLTZero = lumaMM < 0.0;\n/*--------------------------------------------------------------------------*/\n lumaEndN -= lumaNN * 0.5;\n lumaEndP -= lumaNN * 0.5;\n FxaaBool doneN = abs(lumaEndN) >= gradientScaled;\n FxaaBool doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1;\n FxaaBool doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1;\n/*--------------------------------------------------------------------------*/\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 3)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 4)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 5)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 6)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 7)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 8)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 9)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 10)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 11)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11;\n/*--------------------------------------------------------------------------*/\n #if (FXAA_QUALITY_PS > 12)\n if(doneNP) {\n if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));\n if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));\n if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;\n if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;\n doneN = abs(lumaEndN) >= gradientScaled;\n doneP = abs(lumaEndP) >= gradientScaled;\n if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12;\n if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12;\n doneNP = (!doneN) || (!doneP);\n if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12;\n if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12;\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n #endif\n/*--------------------------------------------------------------------------*/\n }\n/*--------------------------------------------------------------------------*/\n FxaaFloat dstN = posM.x - posN.x;\n FxaaFloat dstP = posP.x - posM.x;\n if(!horzSpan) dstN = posM.y - posN.y;\n if(!horzSpan) dstP = posP.y - posM.y;\n/*--------------------------------------------------------------------------*/\n FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero;\n FxaaFloat spanLength = (dstP + dstN);\n FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero;\n FxaaFloat spanLengthRcp = 1.0/spanLength;\n/*--------------------------------------------------------------------------*/\n FxaaBool directionN = dstN < dstP;\n FxaaFloat dst = min(dstN, dstP);\n FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP;\n FxaaFloat subpixG = subpixF * subpixF;\n FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5;\n FxaaFloat subpixH = subpixG * fxaaQualitySubpix;\n/*--------------------------------------------------------------------------*/\n FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0;\n FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH);\n if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign;\n if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign;\n\n #if (FXAA_DISCARD == 1)\n return FxaaTexTop(tex, posM);\n #else\n return FxaaTexTop(tex, posM);\n #endif\n}\n/*==========================================================================*/\n#endif"; // eslint-disable-line
15114
+ PostProcessUberPass.UBER_SHADER_NAME = "PostProcess/Uber";
15498
15115
 
15499
15116
  /**
15500
15117
  * @internal
@@ -15505,17 +15122,11 @@ var FXAA3_11 = "//--------------------------------------------------------------
15505
15122
  var _this;
15506
15123
  _this = PipelinePass.call(this, engine) || this;
15507
15124
  // SRGB Material
15508
- var sRGBmaterial = new Material(engine, Shader.find("FinalSRGB"));
15509
- var sRGBdepthState = sRGBmaterial.renderState.depthState;
15510
- sRGBdepthState.enabled = false;
15511
- sRGBdepthState.writeEnabled = false;
15125
+ var sRGBmaterial = new Material(engine, Shader.find("PostProcess/FinalSRGB"));
15512
15126
  sRGBmaterial._addReferCount(1);
15513
15127
  _this._sRGBmaterial = sRGBmaterial;
15514
15128
  // FXAA Material
15515
- var antiAliasingMaterial = new Material(engine, Shader.find("FinalAntiAliasing"));
15516
- var antiAliasingDepthState = antiAliasingMaterial.renderState.depthState;
15517
- antiAliasingDepthState.enabled = false;
15518
- antiAliasingDepthState.writeEnabled = false;
15129
+ var antiAliasingMaterial = new Material(engine, Shader.find("PostProcess/FinalAntiAliasing"));
15519
15130
  antiAliasingMaterial._addReferCount(1);
15520
15131
  _this._antiAliasingMaterial = antiAliasingMaterial;
15521
15132
  return _this;
@@ -15553,11 +15164,6 @@ var FXAA3_11 = "//--------------------------------------------------------------
15553
15164
  };
15554
15165
  return FinalPass;
15555
15166
  }(PipelinePass);
15556
- Object.assign(ShaderLib, {
15557
- FXAA3_11: FXAA3_11
15558
- });
15559
- Shader.create("FinalSRGB", blitVs, SRGBFS);
15560
- Shader.create("FinalAntiAliasing", blitVs, FinalAntiAliasingFS);
15561
15167
 
15562
15168
  /**
15563
15169
  * @internal
@@ -15632,7 +15238,7 @@ Shader.create("FinalAntiAliasing", blitVs, FinalAntiAliasingFS);
15632
15238
  var compileMacros = Shader._compileMacros;
15633
15239
  var primitive = subElement.primitive, shaderPasses = subElement.shaderPasses, renderElementShaderData = subElement.shaderData;
15634
15240
  var rendererData = renderer.shaderData, rendererId = renderer.instanceId;
15635
- var materialData = material.shaderData, materialId = material.instanceId, renderStates = material.renderStates;
15241
+ var materialData = material.shaderData, materialId = material.instanceId;
15636
15242
  // Union render global macro and material self macro
15637
15243
  ShaderMacroCollection.unionCollection(renderer._globalShaderMacro, materialData._macroCollection, compileMacros);
15638
15244
  ShaderMacroCollection.unionCollection(compileMacros, engine._macroCollection, compileMacros);
@@ -15642,19 +15248,8 @@ Shader.create("FinalAntiAliasing", blitVs, FinalAntiAliasingFS);
15642
15248
  continue;
15643
15249
  }
15644
15250
  var renderState = shaderPass._renderState;
15645
- if (needMaskType) {
15646
- // Mask don't care render queue type
15647
- if (!renderState) {
15648
- renderState = renderStates[j];
15649
- }
15650
- } else {
15651
- var passQueueType = void 0;
15652
- if (renderState) {
15653
- passQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, materialData);
15654
- } else {
15655
- renderState = renderStates[j];
15656
- passQueueType = renderState.renderQueueType;
15657
- }
15251
+ if (!needMaskType) {
15252
+ var passQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, materialData);
15658
15253
  if (passQueueType !== renderQueueType) {
15659
15254
  continue;
15660
15255
  }
@@ -16876,7 +16471,6 @@ CascadedShadowCasterPass._tempMatrix0 = new engineMath.Matrix();
16876
16471
  for(var i = 0, n = subRenderElements.length; i < n; ++i){
16877
16472
  var subRenderElement = subRenderElements[i];
16878
16473
  var material = subRenderElement.material;
16879
- var renderStates = material.renderStates;
16880
16474
  var materialSubShader = material.shader.subShaders[0];
16881
16475
  var replacementShader = context.replacementShader;
16882
16476
  if (replacementShader) {
@@ -16887,33 +16481,28 @@ CascadedShadowCasterPass._tempMatrix0 = new engineMath.Matrix();
16887
16481
  for(var j = 0, m = replacementSubShaders.length; j < m; j++){
16888
16482
  var subShader = replacementSubShaders[j];
16889
16483
  if (subShader.getTagValue(replacementTag) === materialSubShader.getTagValue(replacementTag)) {
16890
- this.pushRenderElementByType(renderElement, subRenderElement, subShader.passes, renderStates);
16484
+ this.pushRenderElementByType(renderElement, subRenderElement, subShader.passes);
16891
16485
  replacementSuccess = true;
16892
16486
  }
16893
16487
  }
16894
16488
  if (!replacementSuccess && context.replacementFailureStrategy === ReplacementFailureStrategy.KeepOriginalShader) {
16895
- this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes, renderStates);
16489
+ this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes);
16896
16490
  }
16897
16491
  } else {
16898
- this.pushRenderElementByType(renderElement, subRenderElement, replacementSubShaders[0].passes, renderStates);
16492
+ this.pushRenderElementByType(renderElement, subRenderElement, replacementSubShaders[0].passes);
16899
16493
  }
16900
16494
  } else {
16901
- this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes, renderStates);
16495
+ this.pushRenderElementByType(renderElement, subRenderElement, materialSubShader.passes);
16902
16496
  }
16903
16497
  }
16904
16498
  };
16905
- _proto.pushRenderElementByType = function pushRenderElementByType(renderElement, subRenderElement, shaderPasses, renderStates) {
16499
+ _proto.pushRenderElementByType = function pushRenderElementByType(renderElement, subRenderElement, shaderPasses) {
16906
16500
  var cullingResults = this._cullingResults;
16907
16501
  for(var i = 0, n = shaderPasses.length; i < n; i++){
16908
16502
  // Get render queue type
16909
- var renderQueueType = void 0;
16910
16503
  var shaderPass = shaderPasses[i];
16911
16504
  var renderState = shaderPass._renderState;
16912
- if (renderState) {
16913
- renderQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, subRenderElement.material.shaderData);
16914
- } else {
16915
- renderQueueType = renderStates[i].renderQueueType;
16916
- }
16505
+ var renderQueueType = renderState._getRenderQueueByShaderData(shaderPass._renderStateDataMap, subRenderElement.material.shaderData);
16917
16506
  var flag = 1 << renderQueueType;
16918
16507
  subRenderElement.shaderPasses = shaderPasses;
16919
16508
  subRenderElement.renderQueueFlags |= flag;
@@ -16951,7 +16540,8 @@ CascadedShadowCasterPass._tempMatrix0 = new engineMath.Matrix();
16951
16540
  program.uploadAll(program.materialUniformBlock, material.shaderData);
16952
16541
  program.uploadAll(program.cameraUniformBlock, camera.shaderData);
16953
16542
  program.uploadUnGroupTextures();
16954
- (pass._renderState || material.renderState)._applyStates(engine, false, pass._renderStateDataMap, material.shaderData);
16543
+ var renderState = pass._renderState;
16544
+ renderState._applyStates(engine, false, pass._renderStateDataMap, material.shaderData);
16955
16545
  rhi.drawPrimitive(mesh._primitive, mesh.subMesh, program);
16956
16546
  };
16957
16547
  _proto._prepareRender = function _prepareRender(context) {
@@ -23252,14 +22842,10 @@ __decorate([
23252
22842
  0,
23253
22843
  2
23254
22844
  ]); // left-top
23255
- var blitMaterial = new Material(engine, Shader.find("blit"));
22845
+ var blitMaterial = new Material(engine, Shader.find("Blit/Blit"));
23256
22846
  blitMaterial._addReferCount(1);
23257
- blitMaterial.renderState.depthState.enabled = false;
23258
- blitMaterial.renderState.depthState.writeEnabled = false;
23259
- var blitScreenMaterial = new Material(engine, Shader.find("blit-screen"));
22847
+ var blitScreenMaterial = new Material(engine, Shader.find("Blit/BlitScreen"));
23260
22848
  blitScreenMaterial._addReferCount(1);
23261
- blitScreenMaterial.renderState.depthState.enabled = false;
23262
- blitScreenMaterial.renderState.depthState.writeEnabled = false;
23263
22849
  this.blitMaterial = blitMaterial;
23264
22850
  this.blitScreenMaterial = blitScreenMaterial;
23265
22851
  this.blitMesh = this._createBlitMesh(engine, vertices);
@@ -23284,11 +22870,11 @@ __decorate([
23284
22870
  ]);
23285
22871
  this.uintWhiteTexture2D = this._create1x1Texture(engine, 0, TextureFormat.R32G32B32A32_UInt, whitePixel32, false);
23286
22872
  }
23287
- this.spriteDefaultMaterial = this._create2DMaterial(engine, Shader.find("Sprite"));
23288
- this.textDefaultMaterial = this._create2DMaterial(engine, Shader.find("Text"));
22873
+ this.spriteDefaultMaterial = this._create2DMaterial(engine, Shader.find("2D/Sprite"));
22874
+ this.textDefaultMaterial = this._create2DMaterial(engine, Shader.find("2D/Text"));
23289
22875
  this.spriteMaskDefaultMaterial = this._createSpriteMaskMaterial(engine);
23290
- this.meshMagentaMaterial = this._createMagentaMaterial(engine, "unlit");
23291
- this.particleMagentaMaterial = this._createMagentaMaterial(engine, "particle-shader");
22876
+ this.meshMagentaMaterial = this._createMagentaMaterial(engine, "Unlit");
22877
+ this.particleMagentaMaterial = this._createMagentaMaterial(engine, "Effect/Particle");
23292
22878
  }
23293
22879
  var _proto = BasicResources.prototype;
23294
22880
  /**
@@ -23380,28 +22966,17 @@ __decorate([
23380
22966
  };
23381
22967
  _proto._create2DMaterial = function _create2DMaterial(engine, shader) {
23382
22968
  var material = new Material(engine, shader);
23383
- var renderState = material.renderState;
23384
- var target = renderState.blendState.targetBlendState;
23385
- target.enabled = true;
23386
- target.sourceColorBlendFactor = BlendFactor.SourceAlpha;
23387
- target.destinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha;
23388
- target.sourceAlphaBlendFactor = BlendFactor.One;
23389
- target.destinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
23390
- target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
23391
- renderState.depthState.writeEnabled = false;
23392
- renderState.rasterState.cullMode = CullMode.Off;
23393
- renderState.renderQueueType = RenderQueueType.Transparent;
23394
22969
  material.isGCIgnored = true;
23395
22970
  return material;
23396
22971
  };
23397
22972
  _proto._createMagentaMaterial = function _createMagentaMaterial(engine, shaderName) {
23398
- var material = new Material(engine, Shader.find(shaderName));
22973
+ var material = new BaseMaterial(engine, Shader.find(shaderName));
23399
22974
  material.isGCIgnored = true;
23400
22975
  material.shaderData.setColor("material_BaseColor", new engineMath.Color(1.0, 0.0, 1.01, 1.0));
23401
22976
  return material;
23402
22977
  };
23403
22978
  _proto._createSpriteMaskMaterial = function _createSpriteMaskMaterial(engine) {
23404
- var material = new Material(engine, Shader.find("SpriteMask"));
22979
+ var material = new Material(engine, Shader.find("2D/SpriteMask"));
23405
22980
  material.isGCIgnored = true;
23406
22981
  return material;
23407
22982
  };
@@ -26851,167 +26426,6 @@ ParticleBufferUtils.boundsFloatStride = 8;
26851
26426
  ParticleBufferUtils.boundsTimeOffset = 6;
26852
26427
  ParticleBufferUtils.boundsMaxLifetimeOffset = 7;
26853
26428
 
26854
- var blitFs = "#include <common>\n\nuniform mediump sampler2D renderer_BlitTexture;\n#ifdef HAS_TEX_LOD\n\tuniform float renderer_BlitMipLevel;\n#endif\n\nuniform vec4 renderer_SourceScaleOffset;\n\nvarying vec2 v_uv;\n\n#ifdef HAS_TEX_LOD\n\tvec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) {\n\t\tvec4 color = texture2DLodEXT(tex, uv, lod);\n\t\t#ifdef ENGINE_NO_SRGB\n\t\t\tcolor = sRGBToLinear(color);\n\t\t#endif\n\t\treturn color;\n\t}\n#endif\n\nvoid main() {\n\tvec2 uv = v_uv;\n\tuv = uv * renderer_SourceScaleOffset.xy + renderer_SourceScaleOffset.zw;\n\n\t#ifdef HAS_TEX_LOD\n\t\tgl_FragColor = texture2DLodSRGB( renderer_BlitTexture, uv, renderer_BlitMipLevel );\n\t#else\n\t\tgl_FragColor = texture2DSRGB( renderer_BlitTexture, uv );\n\t#endif\n}\n\n"; // eslint-disable-line
26855
-
26856
- var blitScreenFs = "#include <common>\n\nuniform mediump sampler2D renderer_BlitTexture;\n#ifdef HAS_TEX_LOD\n\tuniform float renderer_BlitMipLevel;\n#endif\n\nvarying vec2 v_uv;\n\n#ifdef HAS_TEX_LOD\n\tvec4 texture2DLodSRGB(sampler2D tex, vec2 uv, float lod) {\n\t\tvec4 color = texture2DLodEXT(tex, uv, lod);\n\t\t#ifdef ENGINE_NO_SRGB\n\t\t\tcolor = sRGBToLinear(color);\n\t\t#endif\n\t\treturn color;\n\t}\n#endif\n\nvoid main() {\n\tvec2 uv = v_uv;\n\t// Screen uv is flipped\n\tuv.y = 1.0 - uv.y;\n\n\t#ifdef HAS_TEX_LOD\n\t\tgl_FragColor = texture2DLodSRGB( renderer_BlitTexture, uv, renderer_BlitMipLevel );\n\t#else\n\t\tgl_FragColor = texture2D( renderer_BlitTexture, uv );\n\t#endif\n\n\t// Color space in screen is in gamma space but without sRGB texture, so we need to convert it to linear space manually\n\tgl_FragColor = sRGBToLinear(gl_FragColor);\n}\n\n"; // eslint-disable-line
26857
-
26858
- var skyProceduralFs = "// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. \n// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader)\n\n#include <common>\n\nconst float MIE_G = -0.990;\nconst float MIE_G2 = 0.9801;\nconst float SKY_GROUND_THRESHOLD = 0.02;\n\nuniform float material_SunSize;\nuniform float material_SunSizeConvergence;\nuniform vec4 scene_SunlightColor;\nuniform vec3 scene_SunlightDirection;\n\nvarying vec3 v_GroundColor;\nvarying vec3 v_SkyColor;\n\n#ifdef MATERIAL_SUN_HIGH_QUALITY\n\tvarying vec3 v_Vertex;\n#elif defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_RayDir;\n#else\n\tvarying float v_SkyGroundFactor;\n#endif\n\n#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_SunColor;\n#endif\n\n// Calculates the Mie phase function\nfloat getMiePhase(float eyeCos, float eyeCos2) {\n\tfloat temp = 1.0 + MIE_G2 - 2.0 * MIE_G * eyeCos;\n\ttemp = pow(temp, pow(material_SunSize,0.65) * 10.0);\n\ttemp = max(temp,1.0e-4); // prevent division by zero, esp. in half precision\n\ttemp = 1.5 * ((1.0 - MIE_G2) / (2.0 + MIE_G2)) * (1.0 + eyeCos2) / temp;\n\treturn temp;\n}\n\n// Calculates the sun shape\nfloat calcSunAttenuation(vec3 lightPos, vec3 ray) {\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY\n\t\tfloat focusedEyeCos = pow(clamp(dot(lightPos, ray),0.0,1.0), material_SunSizeConvergence);\n\t\treturn getMiePhase(-focusedEyeCos, focusedEyeCos * focusedEyeCos);\n\t#else //MATERIAL_SUN_SIMPLE\n\t\tvec3 delta = lightPos - ray;\n\t\tfloat dist = length(delta);\n\t\tfloat spot = 1.0 - smoothstep(0.0, material_SunSize, dist);\n\t\treturn spot * spot;\n\t#endif\n}\n\nvoid main() {\n\t// if y > 1 [eyeRay.y < -SKY_GROUND_THRESHOLD] - ground\n\t// if y >= 0 and < 1 [eyeRay.y <= 0 and > -SKY_GROUND_THRESHOLD] - horizon\n\t// if y < 0 [eyeRay.y > 0] - sky\n\tvec3 col = vec3(0.0, 0.0, 0.0);\n\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY\n\t\tvec3 ray = normalize(v_Vertex);\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\n\t#elif defined(MATERIAL_SUN_SIMPLE) \n\t\tvec3 ray = v_RayDir;\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\t\n\t#else\n\t\tfloat y = v_SkyGroundFactor;\n\t#endif\n\n\t// if we did precalculate color in vprog: just do lerp between them\n\tcol = mix(v_SkyColor, v_GroundColor, clamp(y,0.0,1.0));\n\n\t#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE)\n\t\tif (y < 0.0)\n\t\t\tcol += v_SunColor * calcSunAttenuation(-scene_SunlightDirection, -ray);\n\t#endif\n\n\n\tgl_FragColor = vec4(col, 1.0);\n}\n\n"; // eslint-disable-line
26859
-
26860
- var skyProceduralVs = "// This code uses the Unity skybox-Procedural shader algorithm, developed by Unity and licensed under the Unity Companion License. \n// The original implementation can be found at unity build-in shader(DefaultResourcesExtra/Skybox-Procedural.shader)\n\n#define OUTER_RADIUS 1.025\n#define RAYLEIGH (mix(0.0, 0.0025, pow(material_AtmosphereThickness,2.5)))\t// Rayleigh constant\n#define MIE 0.0010\t// Mie constant\n#define SUN_BRIGHTNESS 20.0\t// Sun brightness\n#define MAX_SCATTER 50.0 // Maximum scattering value, to prevent math overflows on Adrenos\n\nconst float SKY_GROUND_THRESHOLD = 0.02;\nconst float outerRadius = OUTER_RADIUS;\nconst float outerRadius2 = OUTER_RADIUS*OUTER_RADIUS;\nconst float innerRadius = 1.0;\nconst float innerRadius2 = 1.0;\nconst float cameraHeight = 0.0001;\n\nconst float HDSundiskIntensityFactor = 15.0;\nconst float simpleSundiskIntensityFactor = 27.0;\n\nconst float sunScale = 400.0 * SUN_BRIGHTNESS;\nconst float kmESun = MIE * SUN_BRIGHTNESS;\nconst float km4PI = MIE * 4.0 * 3.14159265;\nconst float scale = 1.0 / (OUTER_RADIUS - 1.0);\nconst float scaleDepth = 0.25;\nconst float scaleOverScaleDepth = (1.0 / (OUTER_RADIUS - 1.0)) / 0.25;\nconst float samples = 2.0; // THIS IS UNROLLED MANUALLY, DON'T TOUCH\n\n// RGB wavelengths .35 (.62=158), .43 (.68=174), .525 (.75=190)\nconst vec3 c_DefaultScatteringWavelength = vec3(0.65, 0.57, 0.475);\nconst vec3 c_VariableRangeForScatteringWavelength = vec3(0.15, 0.15, 0.15);\n\nattribute vec4 POSITION;\n\nuniform mat4 camera_VPMat;\nuniform vec3 material_SkyTint;\nuniform vec3 material_GroundTint;\nuniform float material_Exposure;\nuniform float material_AtmosphereThickness;\nuniform vec4 scene_SunlightColor;\nuniform vec3 scene_SunlightDirection;\n\nvarying vec3 v_GroundColor;\nvarying vec3 v_SkyColor;\n\n#ifdef MATERIAL_SUN_HIGH_QUALITY\n\tvarying vec3 v_Vertex;\n#elif defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_RayDir;\n#else\n\tvarying float v_SkyGroundFactor;\n#endif\n\n#if defined(MATERIAL_SUN_HIGH_QUALITY)||defined(MATERIAL_SUN_SIMPLE)\n\tvarying vec3 v_SunColor;\n#endif\n\n#define GAMMA 2.2\n#define COLOR_2_GAMMA(color) pow(color,vec3(1.0/GAMMA))\n#define COLOR_2_LINEAR(color) color\n\n// Calculates the Rayleigh phase function\nfloat getRayleighPhase(vec3 light, vec3 ray) \n{\n\tfloat eyeCos = dot(light, ray);\n\treturn 0.75 + 0.75 * eyeCos * eyeCos;\n}\n\nfloat scaleAngle(float inCos)\n{\n\tfloat x = 1.0 - inCos;\n\treturn 0.25 * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));\n}\n\nvoid main () {\n\tgl_Position = camera_VPMat*vec4(POSITION.xyz,1.0);\n\n \tvec3 skyTintInGammaSpace = COLOR_2_GAMMA(material_SkyTint);\n\tvec3 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\n\tvec3 invWavelength = 1.0 / pow(scatteringWavelength, vec3(4.0));\n\n\tfloat krESun = RAYLEIGH * SUN_BRIGHTNESS;\n\tfloat kr4PI = RAYLEIGH * 4.0 * 3.14159265;\n\n\tvec3 cameraPos = vec3(0.0,innerRadius + cameraHeight,0.0); // The camera's current position\n\n\t// Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere)\n\tvec3 eyeRay = normalize(POSITION.xyz);\n\n\tfloat far = 0.0;\n\tvec3 cIn, cOut;\n\tif (eyeRay.y >= 0.0) {\n\t\t// Sky \n\t\t// Calculate the length of the \"atmosphere\"\n\t\tfar = sqrt(outerRadius2 + innerRadius2 * eyeRay.y * eyeRay.y - innerRadius2) - innerRadius * eyeRay.y;\n\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\n\t\tfloat height = innerRadius + cameraHeight;\n\t\tfloat depth = exp(scaleOverScaleDepth * -cameraHeight);\n\t\tfloat startAngle = dot(eyeRay, cameraPos) / height;\n\t\tfloat startOffset = depth*scaleAngle(startAngle);\n\n\t\t// Initialize the scattering loop variables\n\t\tfloat sampleLength = far / samples;\n\t\tfloat scaledLength = sampleLength * scale;\n\t\tvec3 sampleRay = eyeRay * sampleLength;\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\n\n\t\tvec3 frontColor = vec3(0.0);\n\t\t//unrolling this manually to avoid some platform for loop slow\n\t\t{\n\t\t\tfloat height = length(samplePoint);\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\n\t\t\tfloat lightAngle = dot(-scene_SunlightDirection, samplePoint) / height;\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\n\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\n\t\t\tsamplePoint += sampleRay;\n\t\t}\n\t\t{\n\t\t\tfloat height = length(samplePoint);\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\n\t\t\tfloat lightAngle = dot(-scene_SunlightDirection, samplePoint) / height;\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\n\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\n\t\t\tsamplePoint += sampleRay;\n\t\t}\n\n\t\t// Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader\n\t\tcIn = frontColor * (invWavelength * krESun);\n\t\tcOut = frontColor * kmESun;\n\t} else {\n\t\t// Ground\n\t\tfar = (-cameraHeight) / (min(-0.001, eyeRay.y));\n\t\tvec3 pos = cameraPos + far * eyeRay;\n\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\n\t\tfloat depth = exp((-cameraHeight) * (1.0/scaleDepth));\n\t\tfloat cameraAngle = dot(-eyeRay, pos);\n\t\tfloat lightAngle = dot(-scene_SunlightDirection, pos);\n\t\tfloat cameraScale = scaleAngle(cameraAngle);\n\t\tfloat lightScale = scaleAngle(lightAngle);\n\t\tfloat cameraOffset = depth*cameraScale;\n\t\tfloat temp = lightScale + cameraScale;\n\n\t\t// Initialize the scattering loop variables\n\t\tfloat sampleLength = far / samples;\n\t\tfloat scaledLength = sampleLength * scale;\n\t\tvec3 sampleRay = eyeRay * sampleLength;\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\n\n\t\t// Now loop through the sample rays\n\t\tvec3 frontColor = vec3(0.0, 0.0, 0.0);\n\t\tvec3 attenuate;\n\n\t\t// Loop removed because we kept hitting SM2.0 temp variable limits. Doesn't affect the image too much\n\t\t{\n\t\t\tfloat height = length(samplePoint);\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\n\t\t\tfloat scatter = depth*temp - cameraOffset;\n\t\t\tattenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\n\t\t\tsamplePoint += sampleRay;\n\t\t}\n\n\t\tcIn = frontColor * (invWavelength * krESun + kmESun);\n\t\tcOut = clamp(attenuate, 0.0, 1.0);\n\t}\n\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY\n\t\tv_Vertex = -POSITION.xyz;\n\t#elif defined(MATERIAL_SUN_SIMPLE) \n\t\tv_RayDir = -eyeRay;\n\t#else\n\t\tv_SkyGroundFactor = -eyeRay.y / SKY_GROUND_THRESHOLD;\n\t#endif\n\n\t// if we want to calculate color in vprog:\n\t// 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)\n\t// 2. in case of gamma: do sqrt right away instead of doing that in fshader\n\t\n\tv_GroundColor = material_Exposure * (cIn + COLOR_2_LINEAR(material_GroundTint) * cOut);\n\tv_SkyColor = material_Exposure * (cIn * getRayleighPhase(-scene_SunlightDirection, -eyeRay));\n\n\t\n\t// The sun should have a stable intensity in its course in the sky. Moreover it should match the highlight of a purely specular material.\n\t// This matching was done using the standard shader BRDF1 on the 5/31/2017\n\t// Finally we want the sun to be always bright even in LDR thus the normalization of the lightColor for low intensity.\n\tfloat lightColorIntensity = clamp(length(scene_SunlightColor.xyz), 0.25, 1.0);\n\n\t#ifdef MATERIAL_SUN_HIGH_QUALITY \n\t\tv_SunColor = HDSundiskIntensityFactor * clamp(cOut,0.0,1.0) * scene_SunlightColor.xyz / lightColorIntensity;\n\t#elif defined(MATERIAL_SUN_SIMPLE) \n\t\tv_SunColor = simpleSundiskIntensityFactor * clamp(cOut * sunScale,0.0,1.0) * scene_SunlightColor.xyz / lightColorIntensity;\n\t#endif\n}\n"; // eslint-disable-line
26861
-
26862
- var backgroundTextureFs = "#include <common>\nuniform sampler2D material_BaseTexture;\n\nvarying vec2 v_uv;\n\nvoid main() {\n gl_FragColor = texture2DSRGB(material_BaseTexture, v_uv);\n}"; // eslint-disable-line
26863
-
26864
- var backgroundTextureVs = "attribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\nvarying vec2 v_uv;\nuniform vec4 camera_ProjectionParams;\n\nvoid main() {\n gl_Position = vec4(POSITION, 1.0);\n gl_Position.y *= camera_ProjectionParams.x;\n \n v_uv = TEXCOORD_0;\n}"; // eslint-disable-line
26865
-
26866
- var blinnPhongFs = "#include <common>\n#include <camera_declare>\n\n#include <uv_share>\n#include <normal_share>\n#include <color_share>\n#include <worldpos_share>\n\n#include <light_frag_define>\n#include <ShadowFragmentDeclaration>\n#include <mobile_material_frag>\n\n#include <FogFragmentDeclaration>\n#include <normal_get>\n\nvoid main() {\n\n #include <begin_mobile_frag>\n #include <begin_viewdir_frag>\n #include <mobile_blinnphong_frag>\n\n gl_FragColor = emission + ambient + diffuse + specular;\n\n #ifdef MATERIAL_IS_TRANSPARENT\n gl_FragColor.a = diffuse.a;\n #else\n gl_FragColor.a = 1.0;\n #endif\n\n #include <FogFragment>\n}\n"; // eslint-disable-line
26867
-
26868
- var blinnPhongVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <uv_share>\n#include <color_share>\n#include <normal_share>\n#include <worldpos_share>\n\n#include <ShadowVertexDeclaration>\n#include <FogVertexDeclaration>\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <begin_normal_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n #include <color_vert>\n #include <normal_vert>\n #include <worldpos_vert>\n #include <position_vert>\n\n #include <ShadowVertex>\n #include <FogVertex>\n}\n"; // eslint-disable-line
26869
-
26870
- var depthOnlyFs = "void main() {\n}"; // eslint-disable-line
26871
-
26872
- var depthOnlyVs = "#define MATERIAL_OMIT_NORMAL\n#include <common>\n#include <common_vert>\n#include <blendShape_input>\nuniform mat4 camera_VPMat;\n\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <position_vert>\n\n}\n"; // eslint-disable-line
26873
-
26874
- var particleFs = "#include <common>\n\nvarying vec4 v_Color;\nvarying vec2 v_TextureCoordinate;\nuniform sampler2D material_BaseTexture;\nuniform vec4 material_BaseColor;\n \nuniform mediump vec3 material_EmissiveColor;\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\n#ifdef RENDERER_MODE_MESH\n\tvarying vec4 v_MeshColor;\n#endif\n\nvoid main() {\n\tvec4 color = material_BaseColor * v_Color;\n\n\t#if defined(RENDERER_MODE_MESH) && defined(RENDERER_ENABLE_VERTEXCOLOR)\n\t\tcolor *= v_MeshColor;\n\t#endif\n\n\t#ifdef MATERIAL_HAS_BASETEXTURE\n\t\tcolor *= texture2DSRGB(material_BaseTexture, v_TextureCoordinate);\n\t#endif\n\t\n\t// Emissive\n\tvec3 emissiveRadiance = material_EmissiveColor;\n\t#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n\t\temissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_TextureCoordinate).rgb;\n\t#endif\n\n\tcolor.rgb += emissiveRadiance;\n\n\tgl_FragColor = color;\n}"; // eslint-disable-line
26875
-
26876
- var particleVs = "#if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD)\n attribute vec4 a_CornerTextureCoordinate;\n#endif\n\n#ifdef RENDERER_MODE_MESH\n attribute vec3 POSITION;\n #ifdef RENDERER_ENABLE_VERTEXCOLOR\n attribute vec4 COLOR_0;\n #endif\n attribute vec2 TEXCOORD_0;\n varying vec4 v_MeshColor;\n#endif\n\nattribute vec4 a_ShapePositionStartLifeTime;\nattribute vec4 a_DirectionTime;\nattribute vec4 a_StartColor;\nattribute vec3 a_StartSize;\nattribute vec3 a_StartRotation0;\nattribute float a_StartSpeed;\n\n//#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)\n attribute vec4 a_Random0;\n//#endif\n\n#if defined(RENDERER_TSA_FRAME_RANDOM_CURVES) || defined(RENDERER_VOL_IS_RANDOM_TWO)\n attribute vec4 a_Random1; // x:texture sheet animation random\n#endif\n\n#if defined(RENDERER_FOL_CONSTANT_MODE) || defined(RENDERER_FOL_CURVE_MODE) || defined(RENDERER_LVL_MODULE_ENABLED)\n attribute vec4 a_Random2;\n#endif\n\nattribute vec3 a_SimulationWorldPosition;\nattribute vec4 a_SimulationWorldRotation;\n\n#ifdef RENDERER_TRANSFORM_FEEDBACK\n attribute vec3 a_FeedbackPosition;\n attribute vec3 a_FeedbackVelocity;\n#endif\n\nvarying vec4 v_Color;\n#ifdef MATERIAL_HAS_BASETEXTURE\n attribute vec4 a_SimulationUV;\n varying vec2 v_TextureCoordinate;\n#endif\n\nuniform float renderer_CurrentTime;\nuniform vec3 renderer_Gravity;\nuniform vec3 renderer_WorldPosition;\nuniform vec4 renderer_WorldRotation;\nuniform bool renderer_ThreeDStartRotation;\nuniform int renderer_ScalingMode;\nuniform vec3 renderer_PositionScale;\nuniform vec3 renderer_SizeScale;\nuniform vec3 renderer_PivotOffset;\n\nuniform mat4 camera_ViewMat;\nuniform mat4 camera_ProjMat;\n\n#ifdef RENDERER_MODE_STRETCHED_BILLBOARD\n uniform vec3 camera_Position;\n#endif\nuniform vec3 camera_Forward; // TODO:只有几种广告牌模式需要用\nuniform vec3 camera_Up;\n\nuniform float renderer_StretchedBillboardLengthScale;\nuniform float renderer_StretchedBillboardSpeedScale;\nuniform int renderer_SimulationSpace;\n\n#include <particle_common>\n#include <velocity_over_lifetime_module>\n#include <force_over_lifetime_module>\n#include <color_over_lifetime_module>\n#include <size_over_lifetime_module>\n#include <rotation_over_lifetime_module>\n#include <texture_sheet_animation_module>\n#include <noise_module>\n\nvec3 computeParticlePosition(in vec3 startVelocity, in float age, in float normalizedAge, vec3 gravityVelocity, vec4 worldRotation, inout vec3 localVelocity, inout vec3 worldVelocity) {\n vec3 startPosition = startVelocity * age;\n\n vec3 finalPosition;\n vec3 localPositionOffset = startPosition;\n vec3 worldPositionOffset;\n\n #ifdef _VOL_MODULE_ENABLED\n vec3 lifeVelocity; \n vec3 velocityPositionOffset = computeVelocityPositionOffset(normalizedAge, age, lifeVelocity);\n if (renderer_VOLSpace == 0) {\n localVelocity += lifeVelocity;\n localPositionOffset += velocityPositionOffset;\n } else {\n worldVelocity += lifeVelocity;\n worldPositionOffset += velocityPositionOffset;\n }\n #endif\n\n #ifdef _FOL_MODULE_ENABLED\n vec3 forceVelocity;\n vec3 forcePositionOffset = computeForcePositionOffset(normalizedAge, age, forceVelocity);\n if (renderer_FOLSpace == 0) {\n localVelocity += forceVelocity;\n localPositionOffset += forcePositionOffset;\n } else {\n worldVelocity += forceVelocity;\n worldPositionOffset += forcePositionOffset;\n }\n #endif\n\n finalPosition = rotationByQuaternions(a_ShapePositionStartLifeTime.xyz + localPositionOffset, worldRotation) + worldPositionOffset;\n\n if (renderer_SimulationSpace == 0) {\n finalPosition = finalPosition + renderer_WorldPosition;\n } else if (renderer_SimulationSpace == 1) {\n\t finalPosition = finalPosition + a_SimulationWorldPosition;\n\t}\n\n finalPosition += 0.5 * gravityVelocity * age;\n\n return finalPosition;\n}\n\nvoid main() {\n float age = renderer_CurrentTime - a_DirectionTime.w;\n float normalizedAge = age / a_ShapePositionStartLifeTime.w;\n // normalizedAge >= 0.0: skip stale TF slots whose startTime is from a previous playback (e.g. after StopEmittingAndClear).\n if (normalizedAge >= 0.0 && normalizedAge < 1.0) {\n vec4 worldRotation;\n if (renderer_SimulationSpace == 0) {\n worldRotation = renderer_WorldRotation;\n } else {\n worldRotation = a_SimulationWorldRotation;\n }\n\n vec3 localVelocity;\n vec3 worldVelocity;\n\n #ifdef RENDERER_TRANSFORM_FEEDBACK\n // Transform Feedback mode: position in simulation space (local or world).\n // Local: transform to world; World: use directly.\n vec3 center;\n if (renderer_SimulationSpace == 0) {\n center = rotationByQuaternions(a_FeedbackPosition, worldRotation) + renderer_WorldPosition;\n } else if (renderer_SimulationSpace == 1) {\n center = a_FeedbackPosition;\n }\n localVelocity = a_FeedbackVelocity;\n worldVelocity = vec3(0.0);\n\n #ifdef _VOL_MODULE_ENABLED\n vec3 instantVOLVelocity;\n computeVelocityPositionOffset(normalizedAge, age, instantVOLVelocity);\n if (renderer_VOLSpace == 0) {\n localVelocity += instantVOLVelocity;\n } else {\n worldVelocity += instantVOLVelocity;\n }\n #endif\n #else\n // Original analytical path\n vec3 startVelocity = a_DirectionTime.xyz * a_StartSpeed;\n vec3 gravityVelocity = renderer_Gravity * a_Random0.x * age;\n localVelocity = startVelocity;\n worldVelocity = gravityVelocity;\n vec3 center = computeParticlePosition(startVelocity, age, normalizedAge, gravityVelocity, worldRotation, localVelocity, worldVelocity);\n #endif\n\n #include <sphere_billboard>\n #include <stretched_billboard>\n #include <horizontal_billboard>\n #include <vertical_billboard>\n #include <particle_mesh>\n\n gl_Position = camera_ProjMat * camera_ViewMat * vec4(center, 1.0);\n v_Color = computeParticleColor(a_StartColor, normalizedAge);\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n vec2 simulateUV;\n #if defined(RENDERER_MODE_SPHERE_BILLBOARD) || defined(RENDERER_MODE_STRETCHED_BILLBOARD) || defined(RENDERER_MODE_HORIZONTAL_BILLBOARD) || defined(RENDERER_MODE_VERTICAL_BILLBOARD)\n simulateUV = a_CornerTextureCoordinate.zw * a_SimulationUV.xy + a_SimulationUV.zw;\n v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge);\n #endif\n #ifdef RENDERER_MODE_MESH\n simulateUV = a_SimulationUV.zw + TEXCOORD_0 * a_SimulationUV.xy;\n v_TextureCoordinate = computeParticleUV(simulateUV, normalizedAge);\n #endif\n #endif\n } else {\n\t gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // Discard use out of X(-1,1),Y(-1,1),Z(0,1)\n }\n}"; // eslint-disable-line
26877
-
26878
- var pbrSpecularFs = "#include <common>\n#include <camera_declare>\n\n#include <FogFragmentDeclaration>\n\n#include <uv_share>\n#include <normal_share>\n#include <color_share>\n#include <worldpos_share>\n\n#include <light_frag_define>\n\n\n#include <pbr_frag_define>\n#include <pbr_helper>\n\nvoid main() {\n #include <pbr_frag>\n #include <FogFragment>\n}\n"; // eslint-disable-line
26879
-
26880
- var pbrFs = "#include <common>\n#include <camera_declare>\n#include <transform_declare>\n\n#include <FogFragmentDeclaration>\n#include <PositionClipSpaceDeclaration>\n\n#include <uv_share>\n#include <normal_share>\n#include <color_share>\n#include <worldpos_share>\n\n#include <light_frag_define>\n\n#include <pbr_frag_define>\n#include <pbr_helper>\n\nvoid main() {\n #include <pbr_frag>\n #include <FogFragment>\n}\n"; // eslint-disable-line
26881
-
26882
- var pbrVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <uv_share>\n#include <color_share>\n#include <normal_share>\n#include <worldpos_share>\n\n#include <ShadowVertexDeclaration>\n#include <FogVertexDeclaration>\n#include <PositionClipSpaceDeclaration>\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <begin_normal_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n #include <color_vert>\n #include <normal_vert>\n #include <worldpos_vert>\n #include <position_vert>\n\n #include <ShadowVertex>\n #include <FogVertex>\n #include <PositionClipSpaceVertex>\n}\n"; // eslint-disable-line
26883
-
26884
- var shadowMapFs = "#ifdef ENGINE_NO_DEPTH_TEXTURE\n /**\n * Decompose and save depth value.\n */\n vec4 pack (float depth) {\n // Use rgba 4 bytes with a total of 32 bits to store the z value, and the accuracy of 1 byte is 1/256.\n const vec4 bitShift = vec4(1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0);\n const vec4 bitMask = vec4(1.0/256.0, 1.0/256.0, 1.0/256.0, 0.0);\n\n vec4 rgbaDepth = fract(depth * bitShift); // Calculate the z value of each point\n\n // Cut off the value which do not fit in 8 bits\n rgbaDepth -= rgbaDepth.gbaa * bitMask;\n\n return rgbaDepth;\n }\n#endif\n\n\nuniform vec4 material_BaseColor;\nuniform sampler2D material_BaseTexture;\nuniform float material_AlphaCutoff;\nvarying vec2 v_uv;\n\nvoid main() {\n #if defined(MATERIAL_IS_ALPHA_CUTOFF) || (defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT))\n float alpha = material_BaseColor.a;\n #ifdef MATERIAL_HAS_BASETEXTURE\n alpha *= texture2D(material_BaseTexture, v_uv).a;\n #endif\n \n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if(alpha < material_AlphaCutoff){\n discard;\n }\n #endif\n \n #if defined(SCENE_ENABLE_TRANSPARENT_SHADOW) && defined(MATERIAL_IS_TRANSPARENT)\n // Interleaved gradient noise\n float noise = fract(52.982919 * fract(dot(vec2(0.06711, 0.00584), gl_FragCoord.xy)));\n if (alpha <= noise) {\n discard;\n };\n #endif\n #endif\n\n #ifdef ENGINE_NO_DEPTH_TEXTURE\n gl_FragColor = pack(gl_FragCoord.z);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n #endif\n}"; // eslint-disable-line
26885
-
26886
- var shadowMapVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <normal_share>\n#include <uv_share>\nuniform mat4 camera_VPMat;\nuniform vec2 scene_ShadowBias; // x: depth bias, y: normal bias\nuniform vec3 scene_LightDirection;\n\nvec3 applyShadowBias(vec3 positionWS) {\n positionWS -= scene_LightDirection * scene_ShadowBias.x;\n return positionWS;\n}\n\nvec3 applyShadowNormalBias(vec3 positionWS, vec3 normalWS) {\n float invNdotL = 1.0 - clamp(dot(-scene_LightDirection, normalWS), 0.0, 1.0);\n float scale = invNdotL * scene_ShadowBias.y;\n positionWS += normalWS * vec3(scale);\n return positionWS;\n}\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <begin_normal_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n \n vec4 positionWS = renderer_ModelMat * position;\n\n positionWS.xyz = applyShadowBias(positionWS.xyz);\n #ifndef MATERIAL_OMIT_NORMAL\n #ifdef RENDERER_HAS_NORMAL\n vec3 normalWS = normalize( mat3(renderer_NormalMat) * normal );\n positionWS.xyz = applyShadowNormalBias(positionWS.xyz, normalWS);\n #endif\n #endif\n\n\n vec4 positionCS = camera_VPMat * positionWS;\n positionCS.z = max(positionCS.z, -1.0);// clamp to min ndc z\n\n gl_Position = positionCS;\n\n}\n"; // eslint-disable-line
26887
-
26888
- var skyboxFs = "#include <common>\nuniform samplerCube material_CubeTexture;\n\nvarying vec3 v_cubeUV;\nuniform float material_Exposure;\nuniform vec4 material_TintColor;\n\nvoid main() {\n vec4 textureColor = textureCube( material_CubeTexture, v_cubeUV );\n\n #ifdef ENGINE_NO_SRGB\n textureColor = sRGBToLinear(textureColor);\n #endif\n\n textureColor.rgb *= material_Exposure * material_TintColor.rgb;\n \n gl_FragColor = textureColor;\n}\n"; // eslint-disable-line
26889
-
26890
- var skyboxVs = "#include <common_vert>\n\nuniform mat4 camera_VPMat;\n\nvarying vec3 v_cubeUV;\nuniform float material_Rotation;\n\nvec4 rotateY(vec4 v, float angle) {\n\tconst float deg2rad = 3.1415926 / 180.0;\n\tfloat radian = angle * deg2rad;\n\tfloat sina = sin(radian);\n\tfloat cosa = cos(radian);\n\tmat2 m = mat2(cosa, -sina, sina, cosa);\n\treturn vec4(m * v.xz, v.yw).xzyw;\n}\n\nvoid main() {\n v_cubeUV = POSITION;\n gl_Position = camera_VPMat * rotateY(vec4(POSITION, 1.0), material_Rotation);\n}\n"; // eslint-disable-line
26891
-
26892
- var spriteMaskFs = "uniform sampler2D renderer_MaskTexture;\nuniform float renderer_MaskAlphaCutoff;\nvarying vec2 v_uv;\n\nvoid main()\n{\n vec4 color = texture2D(renderer_MaskTexture, v_uv);\n if (color.a < renderer_MaskAlphaCutoff) {\n discard;\n }\n\n gl_FragColor = color;\n}\n"; // eslint-disable-line
26893
-
26894
- var spriteMaskVs = "uniform mat4 camera_VPMat;\n\nattribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\n\nvarying vec2 v_uv;\n\nvoid main()\n{\n gl_Position = camera_VPMat * vec4(POSITION, 1.0);\n v_uv = TEXCOORD_0;\n}\n"; // eslint-disable-line
26895
-
26896
- var spriteFs = "#include <common>\nuniform sampler2D renderer_SpriteTexture;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n vec4 baseColor = texture2DSRGB(renderer_SpriteTexture, v_uv);\n gl_FragColor = baseColor * v_color;\n}\n"; // eslint-disable-line
26897
-
26898
- var spriteVs = "uniform mat4 renderer_MVPMat;\n\nattribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\nattribute vec4 COLOR_0;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_Position = renderer_MVPMat * vec4(POSITION, 1.0);\n\n v_uv = TEXCOORD_0;\n v_color = COLOR_0;\n}\n"; // eslint-disable-line
26899
-
26900
- var textFs = "uniform sampler2D renderElement_TextTexture;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n vec4 texColor = texture2D(renderElement_TextTexture, v_uv);\n #ifdef GRAPHICS_API_WEBGL2\n float coverage = texColor.r;\n #else\n float coverage = texColor.a;\n #endif\n gl_FragColor = vec4(v_color.rgb, v_color.a * coverage);\n}\n"; // eslint-disable-line
26901
-
26902
- var textVs = "uniform mat4 renderer_MVPMat;\n\nattribute vec3 POSITION;\nattribute vec2 TEXCOORD_0;\nattribute vec4 COLOR_0;\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_Position = renderer_MVPMat * vec4(POSITION, 1.0);\n\n v_uv = TEXCOORD_0;\n v_color = COLOR_0;\n}\n"; // eslint-disable-line
26903
-
26904
- var trailFs = "#include <common>\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\nuniform vec4 material_BaseColor;\n\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\nuniform mediump vec3 material_EmissiveColor;\n#ifdef MATERIAL_HAS_EMISSIVETEXTURE\n uniform sampler2D material_EmissiveTexture;\n#endif\n\nvoid main() {\n vec4 color = material_BaseColor * v_color;\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n color *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n // Emissive\n vec3 emissiveRadiance = material_EmissiveColor;\n #ifdef MATERIAL_HAS_EMISSIVETEXTURE\n emissiveRadiance *= texture2DSRGB(material_EmissiveTexture, v_uv).rgb;\n #endif\n\n color.rgb += emissiveRadiance;\n\n gl_FragColor = color;\n}\n\n"; // eslint-disable-line
26905
-
26906
- var trailVs = "attribute vec4 a_PositionBirthTime; // xyz: World position, w: Birth time (used by CPU only)\nattribute vec4 a_CornerTangent; // x: Corner (-1 or 1), yzw: Tangent direction\nattribute float a_Distance; // Absolute cumulative distance (written once per point)\n\nuniform vec4 renderer_TrailParams; // x: TextureMode (0: Stretch, 1: Tile), y: TextureScaleX, z: TextureScaleY\nuniform vec2 renderer_DistanceParams; // x: HeadDistance, y: TailDistance\nuniform vec3 camera_Position;\nuniform mat4 camera_ViewMat;\nuniform mat4 camera_ProjMat;\nuniform vec2 renderer_WidthCurve[4]; // Width curve (4 keyframes max: x=time, y=value)\nuniform vec4 renderer_ColorKeys[4]; // Color gradient (x=time, yzw=rgb)\nuniform vec2 renderer_AlphaKeys[4]; // Alpha gradient (x=time, y=alpha)\nuniform vec4 renderer_CurveMaxTime; // x: colorMaxTime, y: alphaMaxTime, z: widthMaxTime\n\nvarying vec2 v_uv;\nvarying vec4 v_color;\n\n#include <particle_common>\n\nvoid main() {\n vec3 position = a_PositionBirthTime.xyz;\n float corner = a_CornerTangent.x;\n vec3 tangent = a_CornerTangent.yzw;\n\n // Distance-based relative position: 0=head(newest), 1=tail(oldest)\n float distFromHead = renderer_DistanceParams.x - a_Distance;\n float totalDist = renderer_DistanceParams.x - renderer_DistanceParams.y;\n float relativePos = totalDist > 0.0 ? distFromHead / totalDist : 0.0;\n\n // Billboard: expand perpendicular to tangent and view direction\n vec3 toCamera = normalize(camera_Position - position);\n vec3 right = cross(tangent, toCamera);\n float rightLenSq = dot(right, right);\n if (rightLenSq < 0.000001) {\n right = cross(tangent, vec3(0.0, 1.0, 0.0));\n rightLenSq = dot(right, right);\n if (rightLenSq < 0.000001) {\n right = cross(tangent, vec3(1.0, 0.0, 0.0));\n rightLenSq = dot(right, right);\n }\n }\n right = right * inversesqrt(rightLenSq);\n\n float width = evaluateParticleCurve(renderer_WidthCurve, min(relativePos, renderer_CurveMaxTime.z));\n vec3 worldPosition = position + right * width * 0.5 * corner;\n\n gl_Position = camera_ProjMat * camera_ViewMat * vec4(worldPosition, 1.0);\n\n // u = position along trail (affected by textureMode), v = corner side.\n float u = renderer_TrailParams.x == 0.0 ? relativePos : distFromHead;\n float v = corner * 0.5 + 0.5;\n v_uv = vec2(u * renderer_TrailParams.y, v * renderer_TrailParams.z);\n\n v_color = evaluateParticleGradient(renderer_ColorKeys, renderer_CurveMaxTime.x, renderer_AlphaKeys, renderer_CurveMaxTime.y, relativePos);\n}\n"; // eslint-disable-line
26907
-
26908
- var unlitFs = "#include <common>\n#include <uv_share>\n#include <FogFragmentDeclaration>\n\nuniform vec4 material_BaseColor;\nuniform float material_AlphaCutoff;\n\n#ifdef MATERIAL_HAS_BASETEXTURE\n uniform sampler2D material_BaseTexture;\n#endif\n\nvoid main() {\n vec4 baseColor = material_BaseColor;\n\n #ifdef MATERIAL_HAS_BASETEXTURE\n baseColor *= texture2DSRGB(material_BaseTexture, v_uv);\n #endif\n\n #ifdef MATERIAL_IS_ALPHA_CUTOFF\n if( baseColor.a < material_AlphaCutoff ) {\n discard;\n }\n #endif\n\n gl_FragColor = baseColor;\n\n #ifndef MATERIAL_IS_TRANSPARENT\n gl_FragColor.a = 1.0;\n #endif\n\n #include <FogFragment>\n}\n"; // eslint-disable-line
26909
-
26910
- var unlitVs = "#include <common>\n#include <common_vert>\n#include <blendShape_input>\n#include <uv_share>\n#include <FogVertexDeclaration>\n\nvoid main() {\n\n #include <begin_position_vert>\n #include <blendShape_vert>\n #include <skinning_vert>\n #include <uv_vert>\n #include <position_vert>\n\n #include <FogVertex>\n}\n"; // eslint-disable-line
26911
-
26912
- /**
26913
- * @internal
26914
- * Shared shader definition for Transform Feedback simulation.
26915
- * Multiple simulators using the same shader share a single program pool per engine.
26916
- */ var TransformFeedbackShader = /*#__PURE__*/ function() {
26917
- function TransformFeedbackShader(vertexSource, fragmentSource, feedbackVaryings) {
26918
- this._id = ShaderPass._shaderPassCounter++;
26919
- this.vertexSource = vertexSource;
26920
- this.fragmentSource = fragmentSource;
26921
- this.feedbackVaryings = feedbackVaryings;
26922
- }
26923
- var _proto = TransformFeedbackShader.prototype;
26924
- /**
26925
- * Get or compile a shader program for the given engine and macro combination.
26926
- */ _proto.getProgram = function getProgram(engine, macroCollection) {
26927
- var pool = engine._getShaderProgramPool(this._id);
26928
- var program = pool.get(macroCollection);
26929
- if (program) return program;
26930
- var _ShaderFactory_compilePlatformSource = ShaderFactory.compilePlatformSource(engine, macroCollection, this.vertexSource, this.fragmentSource), vertexSource = _ShaderFactory_compilePlatformSource.vertexSource, fragmentSource = _ShaderFactory_compilePlatformSource.fragmentSource;
26931
- program = new ShaderProgram(engine, vertexSource, fragmentSource, this.feedbackVaryings);
26932
- if (!program.isValid) {
26933
- Logger.error("TransformFeedbackShader: Failed to compile shader program.");
26934
- return null;
26935
- }
26936
- pool.cache(program);
26937
- return program;
26938
- };
26939
- return TransformFeedbackShader;
26940
- }();
26941
-
26942
- /**
26943
- * Internal shader pool.
26944
- * @internal
26945
- */ var ShaderPool = /*#__PURE__*/ function() {
26946
- function ShaderPool() {}
26947
- ShaderPool.init = function init() {
26948
- ShaderPool.particleFeedbackShader = new TransformFeedbackShader("#include <particle_feedback_simulation>", "void main() { discard; }", [
26949
- "v_FeedbackPosition",
26950
- "v_FeedbackVelocity"
26951
- ]);
26952
- var shadowCasterPass = new ShaderPass("ShadowCaster", shadowMapVs, shadowMapFs, {
26953
- pipelineStage: PipelineStage.ShadowCaster
26954
- });
26955
- shadowCasterPass._renderState = new RenderState();
26956
- shadowCasterPass._renderStateDataMap[RenderStateElementKey.RenderQueueType] = BaseMaterial._shadowCasterRenderQueueProp;
26957
- var depthOnlyPass = new ShaderPass("DepthOnly", depthOnlyVs, depthOnlyFs, {
26958
- pipelineStage: PipelineStage.DepthOnly
26959
- });
26960
- depthOnlyPass._renderState = new RenderState();
26961
- depthOnlyPass._renderStateDataMap[RenderStateElementKey.RenderQueueType] = BaseMaterial._depthOnlyRenderQueueProp;
26962
- var basePasses = [
26963
- shadowCasterPass,
26964
- depthOnlyPass
26965
- ];
26966
- var forwardPassTags = {
26967
- pipelineStage: PipelineStage.Forward
26968
- };
26969
- Shader.create("blinn-phong", [].concat([
26970
- new ShaderPass("Forward", blinnPhongVs, blinnPhongFs, forwardPassTags)
26971
- ], basePasses));
26972
- Shader.create("pbr", [].concat([
26973
- new ShaderPass("Forward", pbrVs, pbrFs, forwardPassTags)
26974
- ], basePasses));
26975
- Shader.create("pbr-specular", [].concat([
26976
- new ShaderPass("Forward", pbrVs, pbrSpecularFs, forwardPassTags)
26977
- ], basePasses));
26978
- Shader.create("unlit", [].concat([
26979
- new ShaderPass("Forward", unlitVs, unlitFs, forwardPassTags)
26980
- ], basePasses));
26981
- Shader.create("blit", [
26982
- new ShaderPass("Forward", blitVs, blitFs, forwardPassTags)
26983
- ]);
26984
- Shader.create("blit-screen", [
26985
- new ShaderPass("Forward", blitVs, blitScreenFs, forwardPassTags)
26986
- ]);
26987
- Shader.create("skybox", [
26988
- new ShaderPass("Forward", skyboxVs, skyboxFs, forwardPassTags)
26989
- ]);
26990
- Shader.create("SkyProcedural", [
26991
- new ShaderPass("Forward", skyProceduralVs, skyProceduralFs, forwardPassTags)
26992
- ]);
26993
- Shader.create("particle-shader", [
26994
- new ShaderPass("Forward", particleVs, particleFs, forwardPassTags)
26995
- ]);
26996
- Shader.create("trail", [
26997
- new ShaderPass("Forward", trailVs, trailFs, forwardPassTags)
26998
- ]);
26999
- Shader.create("SpriteMask", [
27000
- new ShaderPass("Forward", spriteMaskVs, spriteMaskFs, forwardPassTags)
27001
- ]);
27002
- Shader.create("Sprite", [
27003
- new ShaderPass("Forward", spriteVs, spriteFs, forwardPassTags)
27004
- ]);
27005
- Shader.create("Text", [
27006
- new ShaderPass("Forward", textVs, textFs, forwardPassTags)
27007
- ]);
27008
- Shader.create("background-texture", [
27009
- new ShaderPass("Forward", backgroundTextureVs, backgroundTextureFs, forwardPassTags)
27010
- ]);
27011
- };
27012
- return ShaderPool;
27013
- }();
27014
-
27015
26429
  /**
27016
26430
  * Shader program pool.
27017
26431
  * @internal
@@ -27181,7 +26595,6 @@ var OverlayCamera = function OverlayCamera() {
27181
26595
  return XRManager;
27182
26596
  }();
27183
26597
 
27184
- ShaderPool.init();
27185
26598
  /**
27186
26599
  * Engine.
27187
26600
  */ var Engine = /*#__PURE__*/ function(EventDispatcher) {
@@ -27516,9 +26929,17 @@ ShaderPool.init();
27516
26929
  * @internal
27517
26930
  */ _proto._initialize = function _initialize(configuration) {
27518
26931
  var _this = this;
27519
- var shaderLab = configuration.shaderLab, physics = configuration.physics;
27520
- if (shaderLab && !Shader._shaderLab) {
27521
- Shader._shaderLab = shaderLab;
26932
+ var shaderCompiler = configuration.shaderCompiler, physics = configuration.physics;
26933
+ if (shaderCompiler && !Shader._shaderCompiler) {
26934
+ // Bind the runtime include map so the preprocessor sees every chunk
26935
+ // the umbrella package's ShaderPool registered into ShaderFactory.
26936
+ // shader-compiler defaults to an empty map and stays free of any direct
26937
+ // ShaderFactory dependency, so the binding has to be wired here at the
26938
+ // runtime boundary.
26939
+ // @ts-ignore — `_setIncludeMap` is shader-compiler @internal; `includeMap`
26940
+ // is `ShaderFactory` @internal. Both intentionally cross-package wired.
26941
+ shaderCompiler._setIncludeMap(ShaderFactory.includeMap);
26942
+ Shader._shaderCompiler = shaderCompiler;
27522
26943
  }
27523
26944
  var initializePromises = new Array();
27524
26945
  if (physics) {
@@ -28028,18 +27449,36 @@ ShaderPool.init();
28028
27449
  }
28029
27450
  };
28030
27451
  _proto.isStencilWritten = function isStencilWritten(material) {
28031
- var stencilState = material.renderState.stencilState;
28032
- var stencilOperation = StencilOperation.Keep;
28033
- if (stencilState.enabled && stencilState.writeMask !== 0x00 && (stencilState.passOperationFront !== stencilOperation || stencilState.passOperationBack !== stencilOperation || stencilState.failOperationFront !== stencilOperation || stencilState.failOperationBack !== stencilOperation || stencilState.zFailOperationFront !== stencilOperation || stencilState.zFailOperationBack !== stencilOperation)) {
28034
- return true;
28035
- }
27452
+ var data = material.shaderData;
27453
+ if (!data.getFloat(MaskManager._stencilEnabledProp)) return false;
27454
+ var _data_getFloat;
27455
+ if (((_data_getFloat = data.getFloat(MaskManager._stencilWriteMaskProp)) != null ? _data_getFloat : 0xff) === 0) return false;
27456
+ var keep = StencilOperation.Keep;
27457
+ var passFront = data.getFloat(MaskManager._stencilPassOperationFrontProp);
27458
+ if (passFront !== undefined && passFront !== keep) return true;
27459
+ var passBack = data.getFloat(MaskManager._stencilPassOperationBackProp);
27460
+ if (passBack !== undefined && passBack !== keep) return true;
27461
+ var failFront = data.getFloat(MaskManager._stencilFailOperationFrontProp);
27462
+ if (failFront !== undefined && failFront !== keep) return true;
27463
+ var failBack = data.getFloat(MaskManager._stencilFailOperationBackProp);
27464
+ if (failBack !== undefined && failBack !== keep) return true;
27465
+ var zFailFront = data.getFloat(MaskManager._stencilZFailOperationFrontProp);
27466
+ if (zFailFront !== undefined && zFailFront !== keep) return true;
27467
+ var zFailBack = data.getFloat(MaskManager._stencilZFailOperationBackProp);
27468
+ if (zFailBack !== undefined && zFailBack !== keep) return true;
28036
27469
  return false;
28037
27470
  };
28038
27471
  _proto.isReadStencil = function isReadStencil(material) {
28039
- var _material_renderState_stencilState = material.renderState.stencilState, enabled = _material_renderState_stencilState.enabled, mask = _material_renderState_stencilState.mask, compareFunctionFront = _material_renderState_stencilState.compareFunctionFront, compareFunctionBack = _material_renderState_stencilState.compareFunctionBack;
28040
- if (enabled && mask !== 0x00 && (compareFunctionFront !== CompareFunction.Always && compareFunctionFront !== CompareFunction.Never || compareFunctionBack !== CompareFunction.Always && compareFunctionBack !== CompareFunction.Never)) {
28041
- return true;
28042
- }
27472
+ var data = material.shaderData;
27473
+ if (!data.getFloat(MaskManager._stencilEnabledProp)) return false;
27474
+ var _data_getFloat;
27475
+ if (((_data_getFloat = data.getFloat(MaskManager._stencilMaskProp)) != null ? _data_getFloat : 0xff) === 0) return false;
27476
+ var always = CompareFunction.Always;
27477
+ var never = CompareFunction.Never;
27478
+ var cmpFront = data.getFloat(MaskManager._stencilCompareFunctionFrontProp);
27479
+ if (cmpFront !== undefined && cmpFront !== always && cmpFront !== never) return true;
27480
+ var cmpBack = data.getFloat(MaskManager._stencilCompareFunctionBackProp);
27481
+ if (cmpBack !== undefined && cmpBack !== always && cmpBack !== never) return true;
28043
27482
  return false;
28044
27483
  };
28045
27484
  _proto.destroy = function destroy() {
@@ -28079,6 +27518,17 @@ ShaderPool.init();
28079
27518
  };
28080
27519
  return MaskManager;
28081
27520
  }();
27521
+ MaskManager._stencilEnabledProp = ShaderProperty.getByName("stencilEnabled");
27522
+ MaskManager._stencilWriteMaskProp = ShaderProperty.getByName("stencilWriteMask");
27523
+ MaskManager._stencilMaskProp = ShaderProperty.getByName("stencilMask");
27524
+ MaskManager._stencilCompareFunctionFrontProp = ShaderProperty.getByName("stencilCompareFunctionFront");
27525
+ MaskManager._stencilCompareFunctionBackProp = ShaderProperty.getByName("stencilCompareFunctionBack");
27526
+ MaskManager._stencilPassOperationFrontProp = ShaderProperty.getByName("stencilPassOperationFront");
27527
+ MaskManager._stencilPassOperationBackProp = ShaderProperty.getByName("stencilPassOperationBack");
27528
+ MaskManager._stencilFailOperationFrontProp = ShaderProperty.getByName("stencilFailOperationFront");
27529
+ MaskManager._stencilFailOperationBackProp = ShaderProperty.getByName("stencilFailOperationBack");
27530
+ MaskManager._stencilZFailOperationFrontProp = ShaderProperty.getByName("stencilZFailOperationFront");
27531
+ MaskManager._stencilZFailOperationBackProp = ShaderProperty.getByName("stencilZFailOperationBack");
28082
27532
 
28083
27533
  /**
28084
27534
  * Fog Mode.
@@ -33495,9 +32945,7 @@ function _assert_this_initialized(self) {
33495
32945
  _inherits(SkyBoxMaterial, Material);
33496
32946
  function SkyBoxMaterial(engine) {
33497
32947
  var _this;
33498
- _this = Material.call(this, engine, Shader.find("skybox")) || this, _this._tintColor = new engineMath.Color(1, 1, 1, 1);
33499
- _this.renderState.rasterState.cullMode = CullMode.Off;
33500
- _this.renderState.depthState.compareFunction = CompareFunction.LessEqual;
32948
+ _this = Material.call(this, engine, Shader.find("Sky/Skybox")) || this, _this._tintColor = new engineMath.Color(1, 1, 1, 1);
33501
32949
  _this.shaderData.setFloat(SkyBoxMaterial._rotationProp, 0);
33502
32950
  _this.shaderData.setFloat(SkyBoxMaterial._exposureProp, 1);
33503
32951
  _this.shaderData.setColor(SkyBoxMaterial._tintColorProp, _this._tintColor);
@@ -33578,7 +33026,7 @@ SkyBoxMaterial._exposureProp = ShaderProperty.getByName("material_Exposure");
33578
33026
  _inherits(SkyProceduralMaterial, Material);
33579
33027
  function SkyProceduralMaterial(engine) {
33580
33028
  var _this;
33581
- _this = Material.call(this, engine, Shader.find("SkyProcedural")) || this;
33029
+ _this = Material.call(this, engine, Shader.find("Sky/SkyProcedural")) || this;
33582
33030
  _this.sunMode = 2;
33583
33031
  _this.sunSize = 0.04;
33584
33032
  _this.sunSizeConvergence = 5;
@@ -33586,8 +33034,6 @@ SkyBoxMaterial._exposureProp = ShaderProperty.getByName("material_Exposure");
33586
33034
  _this.skyTint = new engineMath.Color(0.21404114048223255, 0.21404114048223255, 0.21404114048223255, 1.0);
33587
33035
  _this.groundTint = new engineMath.Color(0.11216882039252905, 0.09988709277986121, 0.09520561068319185, 1.0);
33588
33036
  _this.exposure = 1.3;
33589
- _this.renderState.rasterState.cullMode = CullMode.Off;
33590
- _this.renderState.depthState.compareFunction = CompareFunction.LessEqual;
33591
33037
  return _this;
33592
33038
  }
33593
33039
  var _proto = SkyProceduralMaterial.prototype;
@@ -34145,10 +33591,10 @@ __decorate([
34145
33591
  * General-purpose Transform Feedback simulator.
34146
33592
  * Manages per-frame simulation with shared shader program caching.
34147
33593
  */ var TransformFeedbackSimulator = /*#__PURE__*/ function() {
34148
- function TransformFeedbackSimulator(engine, byteStride, shader) {
33594
+ function TransformFeedbackSimulator(engine, byteStride, shaderPass) {
34149
33595
  this._engine = engine;
34150
33596
  this._primitive = new TransformFeedbackPrimitive(engine, byteStride);
34151
- this._shader = shader;
33597
+ this._shaderPass = shaderPass;
34152
33598
  }
34153
33599
  var _proto = TransformFeedbackSimulator.prototype;
34154
33600
  /**
@@ -34164,8 +33610,8 @@ __decorate([
34164
33610
  * @param inputBinding - Input buffer binding
34165
33611
  * @param inputElements - Vertex elements for the input buffer
34166
33612
  */ _proto.beginUpdate = function beginUpdate(shaderData, feedbackElements, inputBinding, inputElements) {
34167
- var program = this._shader.getProgram(this._engine, shaderData._macroCollection);
34168
- if (!program) return false;
33613
+ var program = this._shaderPass._getShaderProgram(this._engine, shaderData._macroCollection);
33614
+ if (!(program == null ? void 0 : program.isValid)) return false;
34169
33615
  program.bind();
34170
33616
  program.uploadUniforms(program.rendererUniformBlock, shaderData);
34171
33617
  program.uploadUniforms(program.otherUniformBlock, shaderData);
@@ -34212,13 +33658,23 @@ __decorate([
34212
33658
  return TransformFeedbackSimulator;
34213
33659
  }();
34214
33660
 
33661
+ var FEEDBACK_SHADER_NAME = "Effect/ParticleFeedback";
34215
33662
  /**
34216
33663
  * @internal
34217
33664
  * Particle-specific Transform Feedback simulation.
34218
33665
  */ var ParticleTransformFeedbackSimulator = /*#__PURE__*/ function() {
34219
33666
  function ParticleTransformFeedbackSimulator(engine) {
34220
33667
  this._particleInitData = new Float32Array(6);
34221
- this._simulator = new TransformFeedbackSimulator(engine, ParticleBufferUtils.feedbackVertexStride, ShaderPool.particleFeedbackShader);
33668
+ // Look up the feedback pass dynamically rather than caching it on a
33669
+ // built-in pool — `engine-core` no longer ships the built-in shader set
33670
+ // itself; the umbrella `@galacean/engine` package registers
33671
+ // `Effect/ParticleFeedback` (and configures its transform-feedback
33672
+ // varyings) at module load time.
33673
+ var feedbackShader = Shader.find(FEEDBACK_SHADER_NAME);
33674
+ if (!feedbackShader) {
33675
+ throw new Error("" + FEEDBACK_SHADER_NAME + ' shader is not registered. Import "@galacean/engine" before constructing the engine, ' + "or register the shader manually if you build a custom engine flavor.");
33676
+ }
33677
+ this._simulator = new TransformFeedbackSimulator(engine, ParticleBufferUtils.feedbackVertexStride, feedbackShader.subShaders[0].passes[0]);
34222
33678
  }
34223
33679
  var _proto = ParticleTransformFeedbackSimulator.prototype;
34224
33680
  /**
@@ -38312,7 +37768,7 @@ __decorate([
38312
37768
  */ var ParticleMaterial = /*#__PURE__*/ function(EffectMaterial) {
38313
37769
  _inherits(ParticleMaterial, EffectMaterial);
38314
37770
  function ParticleMaterial(engine) {
38315
- return EffectMaterial.call(this, engine, Shader.find("particle-shader")) || this;
37771
+ return EffectMaterial.call(this, engine, Shader.find("Effect/Particle")) || this;
38316
37772
  }
38317
37773
  var _proto = ParticleMaterial.prototype;
38318
37774
  /**
@@ -39703,7 +39159,7 @@ __decorate([
39703
39159
  */ var TrailMaterial = /*#__PURE__*/ function(EffectMaterial) {
39704
39160
  _inherits(TrailMaterial, EffectMaterial);
39705
39161
  function TrailMaterial(engine) {
39706
- return EffectMaterial.call(this, engine, Shader.find("trail")) || this;
39162
+ return EffectMaterial.call(this, engine, Shader.find("Effect/Trail")) || this;
39707
39163
  }
39708
39164
  var _proto = TrailMaterial.prototype;
39709
39165
  /**
@@ -40389,8 +39845,6 @@ __decorate([
40389
39845
  return Polyfill;
40390
39846
  }();
40391
39847
 
40392
- Polyfill.registerPolyfill();
40393
-
40394
39848
  exports.AmbientLight = AmbientLight;
40395
39849
  exports.AmbientOcclusion = AmbientOcclusion;
40396
39850
  exports.AmbientOcclusionQuality = AmbientOcclusionQuality;
@@ -40427,7 +39881,6 @@ exports.BlendMode = BlendMode;
40427
39881
  exports.BlendOperation = BlendOperation;
40428
39882
  exports.BlendShape = BlendShape;
40429
39883
  exports.BlendShapeFrame = BlendShapeFrame;
40430
- exports.BlendState = BlendState;
40431
39884
  exports.BlinnPhongMaterial = BlinnPhongMaterial;
40432
39885
  exports.Blitter = Blitter;
40433
39886
  exports.BloomDownScaleMode = BloomDownScaleMode;
@@ -40472,7 +39925,6 @@ exports.CullMode = CullMode;
40472
39925
  exports.CurveKey = CurveKey;
40473
39926
  exports.DataType = DataType;
40474
39927
  exports.DependentMode = DependentMode;
40475
- exports.DepthState = DepthState;
40476
39928
  exports.DepthTextureMode = DepthTextureMode;
40477
39929
  exports.DiffuseMode = DiffuseMode;
40478
39930
  exports.DirectLight = DirectLight;
@@ -40552,6 +40004,7 @@ exports.PointerButton = PointerButton;
40552
40004
  exports.PointerEventData = PointerEventData;
40553
40005
  exports.PointerEventEmitter = PointerEventEmitter;
40554
40006
  exports.PointerPhase = PointerPhase;
40007
+ exports.Polyfill = Polyfill;
40555
40008
  exports.PostProcess = PostProcess;
40556
40009
  exports.PostProcessEffect = PostProcessEffect;
40557
40010
  exports.PostProcessEffectBoolParameter = PostProcessEffectBoolParameter;
@@ -40570,7 +40023,6 @@ exports.PostProcessUberPass = PostProcessUberPass;
40570
40023
  exports.Primitive = Primitive;
40571
40024
  exports.PrimitiveMesh = PrimitiveMesh;
40572
40025
  exports.Probe = Probe;
40573
- exports.RasterState = RasterState;
40574
40026
  exports.ReferResource = ReferResource;
40575
40027
  exports.RefractionMode = RefractionMode;
40576
40028
  exports.RenderBufferDepthFormat = RenderBufferDepthFormat;
@@ -40578,10 +40030,8 @@ exports.RenderFace = RenderFace;
40578
40030
  exports.RenderQueue = RenderQueue;
40579
40031
  exports.RenderQueueFlags = RenderQueueFlags;
40580
40032
  exports.RenderQueueType = RenderQueueType;
40581
- exports.RenderState = RenderState;
40582
40033
  exports.RenderStateElementKey = RenderStateElementKey;
40583
40034
  exports.RenderTarget = RenderTarget;
40584
- exports.RenderTargetBlendState = RenderTargetBlendState;
40585
40035
  exports.RendererUpdateFlags = RendererUpdateFlags;
40586
40036
  exports.RenderingStatistics = RenderingStatistics;
40587
40037
  exports.ReplacementFailureStrategy = ReplacementFailureStrategy;
@@ -40598,7 +40048,6 @@ exports.ShaderData = ShaderData;
40598
40048
  exports.ShaderDataGroup = ShaderDataGroup;
40599
40049
  exports.ShaderFactory = ShaderFactory;
40600
40050
  exports.ShaderLanguage = ShaderLanguage;
40601
- exports.ShaderLib = ShaderLib;
40602
40051
  exports.ShaderMacro = ShaderMacro;
40603
40052
  exports.ShaderMacroCollection = ShaderMacroCollection;
40604
40053
  exports.ShaderPass = ShaderPass;
@@ -40631,7 +40080,6 @@ exports.SpriteTileMode = SpriteTileMode;
40631
40080
  exports.StateMachineScript = StateMachineScript;
40632
40081
  exports.StaticCollider = StaticCollider;
40633
40082
  exports.StencilOperation = StencilOperation;
40634
- exports.StencilState = StencilState;
40635
40083
  exports.SubFont = SubFont;
40636
40084
  exports.SubMesh = SubMesh;
40637
40085
  exports.SubPrimitive = SubPrimitive;