@animech-public/playcanvas
Version:
PlayCanvas WebGL game engine
2 lines (1 loc) • 33.4 kB
JavaScript
import{SEMANTIC_POSITION as t,SEMANTIC_ATTR12 as e,SEMANTIC_ATTR13 as i,SEMANTIC_ATTR14 as n,SEMANTIC_ATTR15 as a,SEMANTIC_NORMAL as s,SEMANTIC_TANGENT as r,SEMANTIC_COLOR as o,SEMANTIC_ATTR8 as d,SEMANTIC_ATTR9 as l,SEMANTIC_ATTR10 as p,SEMANTIC_ATTR11 as c,SEMANTIC_BLENDWEIGHT as h,SEMANTIC_BLENDINDICES as g,PIXELFORMAT_RGBA8 as u,SHADERTAG_MATERIAL as f,SEMANTIC_TEXCOORD0 as _,SEMANTIC_TEXCOORD1 as S}from"../../../platform/graphics/constants.js";import{shaderChunks as m}from"../chunks/chunks.js";import{ChunkUtils as A}from"../chunk-utils.js";import{SPRITE_RENDERMODE_SLICED as v,SPRITE_RENDERMODE_TILED as P,LIGHTSHAPE_SPHERE as D,LIGHTSHAPE_DISK as b,LIGHTSHAPE_RECT as C,SHADER_DEPTH as L,SHADER_PREPASS_VELOCITY as w,LIGHTTYPE_DIRECTIONAL as E,SHADOW_VSM32 as $,LIGHTTYPE_OMNI as N,SHADOW_PCSS as W,SHADOW_VSM8 as T,LIGHTSHAPE_PUNCTUAL as M,LIGHTTYPE_SPOT as y,FRESNEL_SCHLICK as R,SPECOCC_GLOSSDEPENDENT as F,SPECOCC_AO as x,SHADOW_PCF3 as I,SHADOW_PCF5 as O,SHADOW_PCF1 as V,SHADOW_VSM16 as k,SPECULAR_PHONG as G,shadowTypeToString as H,LIGHTFALLOFF_LINEAR as B,BLEND_NORMAL as U,BLEND_PREMULTIPLIED as X,BLEND_ADDITIVEALPHA as j,SHADER_PICK as z}from"../../constants.js";import{LightsBuffer as Y}from"../../lighting/lights-buffer.js";import{ShaderPass as q}from"../../shader-pass.js";import{ShaderUtils as Q}from"../../../platform/graphics/shader-utils.js";import{ChunkBuilder as K}from"../chunk-builder.js";import{ShaderGenerator as Z}from"./shader-generator.js";const J={vertex_normal:s,vertex_tangent:r,vertex_texCoord0:_,vertex_texCoord1:S,vertex_color:o,vertex_boneWeights:h,vertex_boneIndices:g},tt={vVertexColor:"vec4",vPositionW:"vec3",vNormalV:"vec3",vNormalW:"vec3",vTangentW:"vec3",vBinormalW:"vec3",vObjectSpaceUpW:"vec3",vUv0:"vec2",vUv1:"vec2"};class et{constructor(e,i){if(this.device=e,this.options=i,this.attributes={vertex_position:t},i.userAttributes)for(const[t,e]of Object.entries(i.userAttributes))this.attributes[e]=t;if(i.chunks){const t=i.chunks;this.chunks=Object.create(m);for(const e in m)if(t.hasOwnProperty(e)){const i=t[e];for(const t in J)J.hasOwnProperty(t)&&i.indexOf(t)>=0&&(this.attributes[t]=J[t]);this.chunks[e]=i}}else this.chunks=m;this.shaderPassInfo=q.get(this.device).getByIndex(i.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=i.lights.length>0||i.dirLightMapEnabled||i.clusteredLightingEnabled,this.reflections=!!i.reflectionSource,this.needsNormal=this.lighting||this.reflections||i.useSpecular||i.ambientSH||i.useHeights||i.enableGGXSpecular||i.clusteredLightingEnabled&&!this.shadowPass||i.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=i.useDynamicRefraction,this.needsScreenSize=i.useDynamicRefraction,this.needsTransforms=i.useDynamicRefraction,this.varyings="",this.varyingDefines="",this.vshader=null,this.frontendDecl=null,this.frontendCode=null,this.frontendFunc=null,this.lightingUv=null,this.defines=[],this.fshader=null}_vsAddBaseCode(t,e,i){return t+=e.baseVS,i.nineSlicedMode!==v&&i.nineSlicedMode!==P||(t+=e.baseNineSlicedVS),t}_vsAddTransformCode(t,e,i,n){return t+=this.chunks.transformVS}_setMapTransform(t,e,i,n){const a=i+100*n;if(!t[3][a]){const s=`texture_${e}MapTransform`;t[0]+=`uniform vec3 ${s}0;\n`,t[0]+=`uniform vec3 ${s}1;\n`,t[1]+=`varying vec2 vUV${n}_${i};\n`,t[2]+=` vUV${n}_${i} = vec2(dot(vec3(uv${n}, 1), ${s}0), dot(vec3(uv${n}, 1), ${s}1));\n`,t[3][a]=!0}return t}_fsGetBaseCode(){const t=this.options,e=this.chunks;let i=this.chunks.basePS;return t.nineSlicedMode===v?i+=e.baseNineSlicedPS:t.nineSlicedMode===P&&(i+=e.baseNineSlicedTiledPS),i}_fsGetStartCode(t,e,i,n){let a=i.startPS;return n.nineSlicedMode===v?a+=i.startNineSlicedPS:n.nineSlicedMode===P&&(a+=i.startNineSlicedTiledPS),a}_getLightSourceShapeString(t){switch(t){case C:return"Rect";case b:return"Disk";case D:return"Sphere";default:return""}}generateVertexShader(t,u,f){const _=this.device,S=this.options,m=this.chunks;let A="",v="";A=this._vsAddBaseCode(A,m,S),v+=" vPositionW = getWorldPosition();\n",this.options.pass!==L&&this.options.pass!==w||(A+="varying float vDepth;\n",A+="#ifndef VIEWMATRIX\n",A+="#define VIEWMATRIX\n",A+="uniform mat4 matrix_view;\n",A+="#endif\n",A+="#ifndef CAMERAPLANES\n",A+="#define CAMERAPLANES\n",A+="uniform vec4 camera_params;\n\n",A+="#endif\n",v+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"),this.options.pass,this.options.useInstancing&&(this.attributes.instance_line1=e,this.attributes.instance_line2=i,this.attributes.instance_line3=n,this.attributes.instance_line4=a,A+=m.instancingVS),this.needsNormal&&(this.attributes.vertex_normal=s,v+=" vNormalW = getNormal();\n","sphereMap"===S.reflectionSource&&_.fragmentUniformsCount<=16&&(A+=m.viewNormalVS,v+=" vNormalV = getViewNormal();\n"),S.hasTangents&&(S.useHeights||S.useNormals||S.enableGGXSpecular)?(this.attributes.vertex_tangent=r,A+=m.tangentBinormalVS,v+=" vTangentW = getTangent();\n",v+=" vBinormalW = getBinormal();\n"):!S.enableGGXSpecular&&_.extStandardDerivatives||(v+=" vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));\n"));for(let e=0;e<2;e++)t[e]&&(this.attributes[`vertex_texCoord${e}`]=`TEXCOORD${e}`,A+=m[`uv${e}VS`],v+=` vec2 uv${e} = getUv${e}();\n`),u[e]&&(v+=` vUv${e} = uv${e};\n`);const P=[A,this.varyings,v,[]];if(f.forEach((t=>{this._setMapTransform(P,t.name,t.id,t.uv)})),A=P[0],this.varyings=P[1],v=P[2],S.vertexColors&&(this.attributes.vertex_color=o,v+=" vVertexColor = vertex_color;\n"),S.useMsdf&&S.msdfTextAttribute&&(this.attributes.vertex_outlineParameters=d,this.attributes.vertex_shadowParameters=l,v+=" unpackMsdfParams();\n",A+=m.msdfVS),S.useMorphPosition||S.useMorphNormal)if(S.useMorphTextureBased){A+="#define MORPHING_TEXTURE_BASED\n",S.useMorphPosition&&(A+="#define MORPHING_TEXTURE_BASED_POSITION\n"),S.useMorphNormal&&(A+="#define MORPHING_TEXTURE_BASED_NORMAL\n"),this.attributes.morph_vertex_id=a;const t=_.isWebGPU?"uint":"float";A+=`attribute ${t} morph_vertex_id;\n`}else A+="#define MORPHING\n",S.useMorphPosition?(this.attributes.morph_pos0=d,this.attributes.morph_pos1=l,this.attributes.morph_pos2=p,this.attributes.morph_pos3=c,A+="#define MORPHING_POS03\n",A+="attribute vec3 morph_pos0;\n",A+="attribute vec3 morph_pos1;\n",A+="attribute vec3 morph_pos2;\n",A+="attribute vec3 morph_pos3;\n"):S.useMorphNormal&&(this.attributes.morph_nrm0=d,this.attributes.morph_nrm1=l,this.attributes.morph_nrm2=p,this.attributes.morph_nrm3=c,A+="#define MORPHING_NRM03\n",A+="attribute vec3 morph_nrm0;\n",A+="attribute vec3 morph_nrm1;\n",A+="attribute vec3 morph_nrm2;\n",A+="attribute vec3 morph_nrm3;\n"),S.useMorphNormal?(this.attributes.morph_nrm4=e,this.attributes.morph_nrm5=i,this.attributes.morph_nrm6=n,this.attributes.morph_nrm7=a,A+="#define MORPHING_NRM47\n",A+="attribute vec3 morph_nrm4;\n",A+="attribute vec3 morph_nrm5;\n",A+="attribute vec3 morph_nrm6;\n",A+="attribute vec3 morph_nrm7;\n"):(this.attributes.morph_pos4=e,this.attributes.morph_pos5=i,this.attributes.morph_pos6=n,this.attributes.morph_pos7=a,A+="#define MORPHING_POS47\n",A+="attribute vec3 morph_pos4;\n",A+="attribute vec3 morph_pos5;\n",A+="attribute vec3 morph_pos6;\n",A+="attribute vec3 morph_pos7;\n");S.skin?(this.attributes.vertex_boneWeights=h,this.attributes.vertex_boneIndices=g,A+=Z.skinCode(_,m),A+="#define SKIN\n"):S.useInstancing&&(A+="#define INSTANCING\n"),S.screenSpace&&(A+="#define SCREENSPACE\n"),S.pixelSnap&&(A+="#define PIXELSNAP\n"),A=this._vsAddTransformCode(A,_,m,S),this.needsNormal&&(A+=m.normalVS),A+="\n",A+=m.startVS,A+=v,A+=m.endVS,A+="}",Object.keys(tt).forEach((t=>{A.indexOf(t)>=0&&(this.varyings+=`varying ${tt[t]} ${t};\n`,this.varyingDefines+=`#define VARYING_${t.toUpperCase()}\n`)}));const D=this.shaderPassInfo.shaderDefines;this.vshader=D+this.varyings+A}_fsGetBeginCode(){let t=this.shaderPassInfo.shaderDefines;for(let e=0;e<this.defines.length;e++)t+=`#define ${this.defines[e]}\n`;return t}_fsGetPickPassCode(){let t=this._fsGetBeginCode();return t+="uniform vec4 uColor;\n",t+=this.varyings,t+=this.varyingDefines,t+=this.frontendDecl,t+=this.frontendCode,t+=Z.begin(),t+=this.frontendFunc,t+=" gl_FragColor = uColor;\n",t+=Z.end(),t}_fsGetDepthPassCode(){const t=this.chunks;let e=this._fsGetBeginCode();return e+="varying float vDepth;\n",e+=this.varyings,e+=this.varyingDefines,e+=t.packDepthPS,e+=this.frontendDecl,e+=this.frontendCode,e+=Z.begin(),e+=this.frontendFunc,e+=" gl_FragColor = packFloat(vDepth);\n",e+=Z.end(),e}_fsGetPrePassVelocityCode(){return this._fsGetDepthPassCode()}_fsGetShadowPassCode(){const t=this.device,e=this.options,i=this.chunks,n=this.varyings,a=this.shaderPassInfo.lightType;let s=this.shaderPassInfo.shadowType;a!==E&&e.clusteredLightingEnabled&&(s!==T&&s!==k&&s!==$&&s!==W||(s=I));let r=this._fsGetBeginCode();t.extStandardDerivatives&&t.isWebGL1&&(r+="uniform vec2 polygonOffset;\n"),s===$?t.textureFloatHighPrecision?r+="#define VSM_EXPONENT 15.0\n\n":r+="#define VSM_EXPONENT 5.54\n\n":s===k&&(r+="#define VSM_EXPONENT 5.54\n\n"),a!==E&&(r+="uniform vec3 view_position;\n",r+="uniform float light_radius;\n"),r+=n,r+=this.varyingDefines,r+=this.frontendDecl,r+=this.frontendCode;const o=s===V||s===I||s===O||s===W,d=a===N&&s!==W&&!e.clusteredLightingEnabled,l=o&&!t.supportsDepthShadow||d;l?r+=i.packDepthPS:s===T&&(r+="vec2 encodeFloatRG( float v ) {\n",r+=" vec2 enc = vec2(1.0, 255.0) * v;\n",r+=" enc = fract(enc);\n",r+=" enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n",r+=" return enc;\n",r+="}\n\n"),s===W&&(r+=m.linearizeDepthPS),r+=Z.begin(),r+=this.frontendFunc;const p=s===T||s===k||s===$,c=t.isWebGL1&&t.extStandardDerivatives;let h=!1;if(a===E||!p&&a===y?r+=" float depth = gl_FragCoord.z;\n":(r+=" float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n",h=!0),c&&(r+=" float minValue = 2.3374370500153186e-10; //(1.0 / 255.0) / (256.0 * 256.0 * 256.0);\n",r+=" depth += polygonOffset.x * max(abs(dFdx(depth)), abs(dFdy(depth))) + minValue * polygonOffset.y;\n",h=!0),l)r+=" gl_FragColor = packFloat(depth);\n";else if(p)r+=s===T?" gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n":i.storeEVSMPS;else{s===W?r+=" gl_FragColor.r = depth;\n":(h&&(r+=" gl_FragDepth = depth;\n"),r+=" gl_FragColor = vec4(1.0);\n")}return r+=Z.end(),r}_fsGetLitPassCode(){const t=this.device,e=this.options,i=this.chunks,n=new K,a=new K,s=new K,r=new K;!1===e.opacityFadesSpecular&&n.append("uniform float material_alphaFade;"),e.useSpecular&&(this.defines.push("LIT_SPECULAR"),this.reflections&&this.defines.push("LIT_REFLECTIONS"),e.useClearCoat&&this.defines.push("LIT_CLEARCOAT"),e.fresnelModel>0&&this.defines.push("LIT_SPECULAR_FRESNEL"),e.conserveEnergy&&this.defines.push("LIT_CONSERVE_ENERGY"),e.useSheen&&this.defines.push("LIT_SHEEN"),e.useIridescence&&this.defines.push("LIT_IRIDESCENCE"));const o=[];let d=0,l=!1,p=!1,c=!1,h=e.lights.some((t=>t._shape&&t._shape!==M));if(e.clusteredLightingEnabled&&e.clusteredLightingAreaLightsEnabled&&(h=!0),h||e.clusteredLightingEnabled){let e="highp";t.areaLightLutFormat===u&&(n.append("#define AREA_R8_G8_B8_A8_LUTS"),e="lowp"),n.append("#define AREA_LIGHTS"),n.append(`uniform ${e} sampler2D areaLightsLutTex1;`),n.append(`uniform ${e} sampler2D areaLightsLutTex2;`)}for(let i=0;i<e.lights.length;i++){const a=e.lights[i],s=a._type;if(e.clusteredLightingEnabled&&s!==E)continue;const r=h&&a._shape?a._shape:M;n.append(`uniform vec3 light${i}_color;`),a._shadowType===W&&a.castShadows&&!e.noShadow&&(n.append(`uniform float light${i}_shadowSearchArea;`),n.append(`uniform vec4 light${i}_cameraParams;`)),s===E?n.append(`uniform vec3 light${i}_direction;`):(n.append(`uniform vec3 light${i}_position;`),n.append(`uniform float light${i}_radius;`),s===y&&(n.append(`uniform vec3 light${i}_direction;`),n.append(`uniform float light${i}_innerConeAngle;`),n.append(`uniform float light${i}_outerConeAngle;`))),r!==M&&(s===E&&n.append(`uniform vec3 light${i}_position;`),n.append(`uniform vec3 light${i}_halfWidth;`),n.append(`uniform vec3 light${i}_halfHeight;`)),a.castShadows&&!e.noShadow&&(n.append(`uniform mat4 light${i}_shadowMatrix;`),n.append(`uniform float light${i}_shadowIntensity;`),s===E&&(n.append(`uniform mat4 light${i}_shadowMatrixPalette[4];`),n.append(`uniform float light${i}_shadowCascadeDistances[4];`),n.append(`uniform float light${i}_shadowCascadeCount;`)),n.append(`uniform vec4 light${i}_shadowParams;`),s===E&&(l=!0),s===N?n.append(`uniform samplerCube light${i}_shadowMap;`):a._isPcf&&t.supportsDepthShadow?n.append(`uniform sampler2DShadow light${i}_shadowMap;`):n.append(`uniform sampler2D light${i}_shadowMap;`),d++,o[a._shadowType]=!0,a._isVsm&&(p=!0),a._shadowType===W&&(c=!0)),a._cookie&&(a._cookie._cubemap?s===N&&(n.append(`uniform samplerCube light${i}_cookie;`),n.append(`uniform float light${i}_cookieIntensity;`),a.castShadows&&!e.noShadow||n.append(`uniform mat4 light${i}_shadowMatrix;`)):s===y&&(n.append(`uniform sampler2D light${i}_cookie;`),n.append(`uniform float light${i}_cookieIntensity;`),a.castShadows&&!e.noShadow||n.append(`uniform mat4 light${i}_shadowMatrix;`),a._cookieTransform&&(n.append(`uniform vec4 light${i}_cookieMatrix;`),n.append(`uniform vec2 light${i}_cookieOffset;`))))}const g=this.needsNormal&&(e.useNormals||e.useClearCoatNormals||e.enableGGXSpecular&&!e.useHeights);if(g&&(e.hasTangents?a.append(e.fastTbn?i.TBNfastPS:i.TBNPS):t.extStandardDerivatives&&(e.useNormals||e.useClearCoatNormals)?a.append(i.TBNderivativePS.replace(/\$UV/g,this.lightingUv)):a.append(i.TBNObjectSpacePS),e.twoSidedLighting&&a.append(i.twoSidedLightingPS)),a.append(i.sphericalPS),a.append(i.decodePS),a.append(Z.gammaCode(e.gamma,i)),a.append(Z.tonemapCode(e.toneMap,i)),a.append(Z.fogCode(e.fog,i)),a.append(this.frontendCode),e.useCubeMapRotation&&n.append("#define CUBEMAP_ROTATION"),this.needsNormal&&(a.append(i.cubeMapRotatePS),a.append(e.cubeMapProjection>0?i.cubeMapProjectBoxPS:i.cubeMapProjectNonePS),a.append(e.skyboxIntensity?i.envMultiplyPS:i.envConstPS)),(this.lighting&&e.useSpecular||this.reflections)&&(e.useMetalness&&a.append(i.metalnessModulatePS),e.fresnelModel===R&&a.append(i.fresnelSchlickPS),e.useIridescence&&a.append(i.iridescenceDiffractionPS)),e.useAo)switch(a.append(i.aoDiffuseOccPS),e.occludeSpecular){case x:a.append(e.occludeSpecularFloat?i.aoSpecOccSimplePS:i.aoSpecOccConstSimplePS);break;case F:a.append(e.occludeSpecularFloat?i.aoSpecOccPS:i.aoSpecOccConstPS)}"envAtlasHQ"===e.reflectionSource?(a.append(e.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),a.append(i.envAtlasPS),a.append(i.reflectionEnvHQPS.replace(/\$DECODE_CUBEMAP/g,A.decodeFunc(e.reflectionCubemapEncoding)).replace(/\$DECODE/g,A.decodeFunc(e.reflectionEncoding)))):"envAtlas"===e.reflectionSource?(a.append(i.envAtlasPS),a.append(i.reflectionEnvPS.replace(/\$DECODE/g,A.decodeFunc(e.reflectionEncoding)))):"cubeMap"===e.reflectionSource?(a.append(e.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),a.append(i.reflectionCubePS.replace(/\$DECODE/g,A.decodeFunc(e.reflectionEncoding)))):"sphereMap"===e.reflectionSource&&a.append(i.reflectionSpherePS.replace(/\$DECODE/g,A.decodeFunc(e.reflectionEncoding))),this.reflections&&(e.useClearCoat&&a.append(i.reflectionCCPS),e.useSheen&&a.append(i.reflectionSheenPS)),e.useRefraction&&(e.useDynamicRefraction?(e.dispersion&&(n.append("uniform float material_dispersion;"),n.append("#define DISPERSION\n")),a.append(i.refractionDynamicPS)):this.reflections&&a.append(i.refractionCubePS)),e.useSheen&&a.append(i.lightSheenPS),e.clusteredLightingEnabled&&(a.append(i.clusteredLightUtilsPS),e.clusteredLightingCookiesEnabled&&a.append(i.clusteredLightCookiesPS),e.clusteredLightingShadowsEnabled&&!e.noShadow&&(o[I]=!0,o[O]=!0,o[W]=!0)),(d>0||e.clusteredLightingEnabled)&&(l&&a.append(i.shadowCascadesPS),(o[V]||o[I])&&a.append(i.shadowStandardPS),o[O]&&!t.isWebGL1&&a.append(i.shadowStandardGL2PS),p&&(a.append(i.shadowVSM_commonPS),o[T]&&a.append(i.shadowVSM8PS),o[k]&&a.append(t.extTextureHalfFloatLinear?i.shadowEVSMPS.replace(/\$/g,"16"):i.shadowEVSMnPS.replace(/\$/g,"16")),o[$]&&a.append(t.extTextureFloatLinear?i.shadowEVSMPS.replace(/\$/g,"32"):i.shadowEVSMnPS.replace(/\$/g,"32"))),c&&(a.append(i.linearizeDepthPS),a.append(i.shadowPCSSPS)),t.isWebGL2||t.isWebGPU||t.extStandardDerivatives||a.append(i.biasConstPS)),e.enableGGXSpecular&&a.append("uniform float material_anisotropy;"),this.lighting&&(a.append(i.lightDiffuseLambertPS),(h||e.clusteredLightingAreaLightsEnabled)&&a.append(i.ltcPS));let f=!1;e.useSpecular&&(this.lighting&&a.append(e.shadingModel===G?i.lightSpecularPhongPS:e.enableGGXSpecular?i.lightSpecularAnisoGGXPS:i.lightSpecularBlinnPS),e.fresnelModel||this.reflections||e.diffuseMapEnabled||(n.append("uniform vec3 material_ambient;"),n.append("#define LIT_OLD_AMBIENT"),f=!0)),a.append(i.combinePS),e.lightMapEnabled&&a.append(e.useSpecular&&e.dirLightMapEnabled?i.lightmapDirAddPS:i.lightmapAddPS);const _=!e.lightMapEnabled||e.lightMapWithoutAmbient;_&&("ambientSH"===e.ambientSource?a.append(i.ambientSHPS):"envAtlas"===e.ambientSource?("envAtlas"!==e.reflectionSource&&"envAtlasHQ"!==e.reflectionSource&&a.append(i.envAtlasPS),a.append(i.ambientEnvPS.replace(/\$DECODE/g,A.decodeFunc(e.ambientEncoding)))):a.append(i.ambientConstantPS)),e.useAmbientTint&&!f&&n.append("uniform vec3 material_ambient;"),e.useMsdf&&(e.msdfTextAttribute||n.append("#define UNIFORM_TEXT_PARAMETERS"),a.append(i.msdfPS)),this.needsNormal&&(a.append(i.viewDirPS),e.useSpecular&&a.append(e.enableGGXSpecular?i.reflDirAnisoPS:i.reflDirPS));let S,m=!1,v=!1,P=!1,D=!1,b=!1;if(e.clusteredLightingEnabled&&this.lighting&&(D=!0,m=!0,v=!0,b=!0,a.append(i.floatUnpackingPS),e.lightMaskDynamic&&n.append("#define CLUSTER_MESH_DYNAMIC_LIGHTS"),e.clusteredLightingCookiesEnabled&&n.append("#define CLUSTER_COOKIES"),e.clusteredLightingShadowsEnabled&&!e.noShadow&&(n.append("#define CLUSTER_SHADOWS"),n.append(`#define CLUSTER_SHADOW_TYPE_${H[e.clusteredLightingShadowType]}`)),e.clusteredLightingAreaLightsEnabled&&n.append("#define CLUSTER_AREALIGHTS"),n.append(Y.getShaderDefines(t)),e.clusteredLightingShadowsEnabled&&!e.noShadow&&a.append(i.clusteredLightShadowsPS),a.append(i.clusteredLightPS)),r.append(this._fsGetStartCode(r,t,i,e)),this.needsNormal&&(r.append(" dVertexNormalW = normalize(vNormalW);"),(e.useHeights||e.useNormals)&&e.hasTangents&&(r.append(" dTangentW = vTangentW;"),r.append(" dBinormalW = vBinormalW;")),r.append(" getViewDir();"),g&&(r.append(" getTBN(dTangentW, dBinormalW, dVertexNormalW);"),e.twoSidedLighting&&r.append(" handleTwoSidedLighting();"))),r.append(this.frontendFunc),this.needsNormal&&(e.useSpecular&&s.append(" getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);"),e.useClearCoat&&s.append(" ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));")),(this.lighting&&e.useSpecular||this.reflections)&&(e.useMetalness&&(s.append(" float f0 = 1.0 / litArgs_ior; f0 = (f0 - 1.0) / (f0 + 1.0); f0 *= f0;"),s.append(" litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);"),s.append(" litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);")),e.useIridescence&&s.append(" vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);")),_&&(s.append(" addAmbient(litArgs_worldNormal);"),e.conserveEnergy&&e.useSpecular&&s.append(" dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);"),e.separateAmbient&&s.append("\n\t\t\t\t\t\t\t\t\t\tvec3 dAmbientLight = dDiffuseLight;\n\t\t\t\t\t\t\t\t\t\tdDiffuseLight = vec3(0);\n\t\t\t\t\t\t\t\t")),e.useAmbientTint&&!f&&s.append(" dDiffuseLight *= material_ambient;"),e.useAo&&!e.occludeDirect&&s.append(" occludeDiffuse(litArgs_ao);"),e.lightMapEnabled&&s.append(" addLightMap(\n\t\t\t\t\t\t\t\tlitArgs_lightmap, \n\t\t\t\t\t\t\t\tlitArgs_lightmapDir, \n\t\t\t\t\t\t\t\tlitArgs_worldNormal, \n\t\t\t\t\t\t\t\tdViewDirW, \n\t\t\t\t\t\t\t\tdReflDirW, \n\t\t\t\t\t\t\t\tlitArgs_gloss, \n\t\t\t\t\t\t\t\tlitArgs_specularity, \n\t\t\t\t\t\t\t\tdVertexNormalW,\n\t\t\t\t\t\t\t\tdTBN\n\t\t\t\t\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\t\t\t\t, iridescenceFresnel,\n\t\t\t\t\t\t\t\tlitArgs_iridescence_intensity\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t\t);"),this.lighting||this.reflections){this.reflections&&(e.useClearCoat&&(s.append(" addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);"),e.fresnelModel>0?(s.append(" ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));"),s.append(" ccReflection.rgb *= ccFresnel;")):s.append(" ccFresnel = 0.0;")),e.useSpecularityFactor&&s.append(" ccReflection.rgb *= litArgs_specularityFactor;"),e.useSheen&&s.append(" addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);"),s.append(" addReflection(dReflDirW, litArgs_gloss);"),e.fresnelModel>0?s.append(" dReflection.rgb *= \n\t\t\t\t\t\t\t\t\t\t\t\tgetFresnel(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdot(dViewDirW, litArgs_worldNormal), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_gloss, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_specularity\n\t\t\t\t\t\t\t\t\t\t\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t, iridescenceFresnel,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_iridescence_intensity\n\t\t\t\t\t\t\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t);"):s.append(" dReflection.rgb *= litArgs_specularity;"),e.useSpecularityFactor&&s.append(" dReflection.rgb *= litArgs_specularityFactor;")),h&&(s.append(" dSpecularLight *= litArgs_specularity;"),e.useSpecular&&s.append(" calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);"));for(let n=0;n<e.lights.length;n++){const r=e.lights[n],o=r._type;if(e.clusteredLightingEnabled&&o!==E)continue;S=!1;const d=h&&r._shape?r.shape:M,l=h&&r._shape?this._getLightSourceShapeString(d):"";if(d!==M&&s.append(` calc${l}LightValues(light${n}_position, light${n}_halfWidth, light${n}_halfHeight);`),o===E?(s.append(` dLightDirNormW = light${n}_direction;`),s.append(" dAtten = 1.0;")):(r._cookie&&(o!==y||r._cookie._cubemap?o===N&&r._cookie._cubemap&&(b=!0,S=!0):(b=!0,S=!0)),s.append(` getLightDirPoint(light${n}_position);`),m=!0,S&&(o===y?s.append(` dAtten3 = getCookie2D${r._cookieFalloff?"":"Clip"}${r._cookieTransform?"Xform":""}(light${n}_cookie, light${n}_shadowMatrix, light${n}_cookieIntensity${r._cookieTransform?`, light${n}_cookieMatrix, light${n}_cookieOffset`:""}).${r._cookieChannel};`):s.append(` dAtten3 = getCookieCube(light${n}_cookie, light${n}_shadowMatrix, light${n}_cookieIntensity).${r._cookieChannel};`)),d===M?r._falloffMode===B?(s.append(` dAtten = getFalloffLinear(light${n}_radius, dLightDirW);`),v=!0):(s.append(` dAtten = getFalloffInvSquared(light${n}_radius, dLightDirW);`),P=!0):(s.append(` dAtten = getFalloffWindow(light${n}_radius, dLightDirW);`),P=!0),s.append(" if (dAtten > 0.00001) {"),o===y&&(S&&!r._cookieFalloff||(s.append(` dAtten *= getSpotEffect(light${n}_direction, light${n}_innerConeAngle, light${n}_outerConeAngle, dLightDirNormW);`),D=!0))),d!==M?o===E?s.append(" dAttenD = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"):s.append(` dAttenD = get${l}LightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW) * 16.0;`):s.append(" dAtten *= getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"),r.castShadows&&!e.noShadow){const e=r._shadowType===W,l=r._shadowType===T||r._shadowType===k||r._shadowType===$,p=r._shadowType===V||r._shadowType===I||r._shadowType===O;let c,h=null;switch(r._shadowType){case T:h="VSM8",c="0.0";break;case k:h="VSM16",c="5.54";break;case $:h="VSM32",c=t.textureFloatHighPrecision?"15.0":"5.54";break;case V:h="PCF1x1";break;case O:h="PCF5x5";break;case W:h="PCSS";break;default:h="PCF3x3"}if(null!==h){r._normalOffsetBias&&!r._isVsm&&a.append("#define SHADOW_SAMPLE_NORMAL_OFFSET"),o===E&&a.append("#define SHADOW_SAMPLE_ORTHO"),((p||e)&&t.isWebGL2||t.isWebGPU||t.extStandardDerivatives)&&a.append("#define SHADOW_SAMPLE_SOURCE_ZBUFFER"),o===N&&a.append("#define SHADOW_SAMPLE_POINT");const g=i.shadowSampleCoordPS;a.append(g.replace("$LIGHT",n)),a.append("#undef SHADOW_SAMPLE_NORMAL_OFFSET"),a.append("#undef SHADOW_SAMPLE_ORTHO"),a.append("#undef SHADOW_SAMPLE_SOURCE_ZBUFFER"),a.append("#undef SHADOW_SAMPLE_POINT");let u=`light${n}_shadowMatrix`;o===E&&r.numCascades>1&&(s.append(` getShadowCascadeMatrix(light${n}_shadowMatrixPalette, light${n}_shadowCascadeDistances, light${n}_shadowCascadeCount);`),u="cascadeShadowMat"),s.append(` dShadowCoord = getShadowSampleCoord${n}(${u}, light${n}_shadowParams, vPositionW, dLightPosW, dLightDirW, dLightDirNormW, dVertexNormalW);`),o===E&&s.append(` fadeShadow(light${n}_shadowCascadeDistances);`);let f=`SHADOWMAP_PASS(light${n}_shadowMap), dShadowCoord, light${n}_shadowParams`;if(l)f=`${f}, ${c}, dLightDirW`;else if(e){let t=`vec2(light${n}_shadowSearchArea)`;d!==M&&(t=`vec2(length(light${n}_halfWidth), length(light${n}_halfHeight)) * light${n}_shadowSearchArea`),f=`${f}, light${n}_cameraParams, ${t}, dLightDirW`}o===N?(h=`Point${h}`,e||(f=`${f}, dLightDirW`)):o===y&&(h=`Spot${h}`),s.append(` float shadow${n} = getShadow${h}(${f});`),s.append(` dAtten *= mix(1.0, shadow${n}, light${n}_shadowIntensity);`)}}if(d!==M?e.conserveEnergy&&e.useSpecular?s.append(` dDiffuseLight += ((dAttenD * dAtten) * light${n}_color${S?" * dAtten3":""}) * (1.0 - dLTCSpecFres);`):s.append(` dDiffuseLight += (dAttenD * dAtten) * light${n}_color${S?" * dAtten3":""};`):h&&e.conserveEnergy&&e.useSpecular?s.append(` dDiffuseLight += (dAtten * light${n}_color${S?" * dAtten3":""}) * (1.0 - litArgs_specularity);`):s.append(` dDiffuseLight += dAtten * light${n}_color${S?" * dAtten3":""};`),e.useSpecular&&s.append(" dHalfDirW = normalize(-dLightDirNormW + dViewDirW);"),r.affectSpecularity)if(d!==M)e.useClearCoat&&s.append(` ccSpecularLight += ccLTCSpecFres * get${l}LightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * light${n}_color${S?" * dAtten3":""};`),e.useSpecular&&s.append(` dSpecularLight += dLTCSpecFres * get${l}LightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * light${n}_color${S?" * dAtten3":""};`);else{let t=!1;o===E&&e.fresnelModel>0&&(t=!0),e.useClearCoat&&s.append(` ccSpecularLight += getLightSpecular(dHalfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * light${n}_color${S?" * dAtten3":""}${t?" * getFresnelCC(dot(dViewDirW, dHalfDirW));":";"}`),e.useSheen&&s.append(` sSpecularLight += getLightSpecularSheen(dHalfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * light${n}_color${S?" * dAtten3;":";"}`),e.useSpecular&&s.append(` dSpecularLight += getLightSpecular(dHalfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * light${n}_color${S?" * dAtten3":""}${t?" \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t* getFresnel(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdot(dViewDirW, dHalfDirW), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_gloss, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_specularity\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, iridescenceFresnel, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_iridescence_intensity\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);":"* litArgs_specularity;"}`)}o!==E&&s.append(" }")}e.clusteredLightingEnabled&&this.lighting&&(v=!0,P=!0,m=!0,s.append(" addClusteredLights(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_worldNormal, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdViewDirW, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdReflDirW,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#if defined(LIT_CLEARCOAT)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tccReflDirW,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_gloss, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_specularity, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdVertexNormalW, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdTBN, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tiridescenceFresnel,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_clearcoat_worldNormal, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_clearcoat_gloss,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_sheen_gloss,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_iridescence_intensity\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);")),h&&(e.useClearCoat&&s.append(" litArgs_clearcoat_specularity = 1.0;"),e.useSpecular&&s.append(" litArgs_specularity = vec3(1);")),e.useRefraction&&s.append(" addRefraction(\n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_worldNormal, \n\t\t\t\t\t\t\t\t\t\t\t\tdViewDirW, \n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_thickness, \n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_gloss, \n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_specularity, \n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_albedo, \n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_transmission,\n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_ior,\n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_dispersion\n\t\t\t\t\t\t\t\t\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\t\t\t\t\t\t\t\t, iridescenceFresnel, \n\t\t\t\t\t\t\t\t\t\t\t\tlitArgs_iridescence_intensity\n\t\t\t\t\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t\t\t\t);")}e.useAo&&(e.occludeDirect&&s.append(" occludeDiffuse(litArgs_ao);"),e.occludeSpecular!==x&&e.occludeSpecular!==F||s.append(" occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);")),e.useSpecularityFactor&&s.append(" dSpecularLight *= litArgs_specularityFactor;"),!1===e.opacityFadesSpecular&&(e.blendType!==U&&e.blendType!==X||(s.append("float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));"),s.append("#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection.rgb * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif"),s.append("litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);")),s.append("litArgs_opacity *= material_alphaFade;")),s.append(i.endPS),e.blendType===U||e.blendType===j||e.alphaToCoverage?s.append(i.outputAlphaPS):e.blendType===X?s.append(i.outputAlphaPremulPS):s.append(i.outputAlphaOpaquePS),e.useMsdf&&s.append(" gl_FragColor = applyMsdf(gl_FragColor);"),s.append(i.outputPS),s.append(i.debugOutputPS),m&&a.prepend(i.lightDirPointPS),v&&a.prepend(i.falloffLinearPS),P&&a.prepend(i.falloffInvSquaredPS),D&&a.prepend(i.spotPS),b&&!e.clusteredLightingEnabled&&a.prepend(i.cookiePS);let C="";const L=`void evaluateBackend() {\n${s.code}\n}`;a.append(L),r.append(i.debugProcessFrontendPS),r.append(" evaluateBackend();"),r.append(Z.end());const w=n.code+a.code+r.code;w.includes("dTBN")&&(C+="mat3 dTBN;\n"),w.includes("dVertexNormalW")&&(C+="vec3 dVertexNormalW;\n"),w.includes("dTangentW")&&(C+="vec3 dTangentW;\n"),w.includes("dBinormalW")&&(C+="vec3 dBinormalW;\n"),w.includes("dViewDirW")&&(C+="vec3 dViewDirW;\n"),w.includes("dReflDirW")&&(C+="vec3 dReflDirW;\n"),w.includes("dHalfDirW")&&(C+="vec3 dHalfDirW;\n"),w.includes("ccReflDirW")&&(C+="vec3 ccReflDirW;\n"),w.includes("dLightDirNormW")&&(C+="vec3 dLightDirNormW;\n"),w.includes("dLightDirW")&&(C+="vec3 dLightDirW;\n"),w.includes("dLightPosW")&&(C+="vec3 dLightPosW;\n"),w.includes("dShadowCoord")&&(C+="vec3 dShadowCoord;\n"),w.includes("dReflection")&&(C+="vec4 dReflection;\n"),w.includes("dDiffuseLight")&&(C+="vec3 dDiffuseLight;\n"),w.includes("dSpecularLight")&&(C+="vec3 dSpecularLight;\n"),w.includes("dAtten")&&(C+="float dAtten;\n"),w.includes("dAttenD")&&(C+="float dAttenD;\n"),w.includes("dAtten3")&&(C+="vec3 dAtten3;\n"),w.includes("dMsdf")&&(C+="vec4 dMsdf;\n"),w.includes("ccFresnel")&&(C+="float ccFresnel;\n"),w.includes("ccReflection")&&(C+="vec3 ccReflection;\n"),w.includes("ccSpecularLight")&&(C+="vec3 ccSpecularLight;\n"),w.includes("ccSpecularityNoFres")&&(C+="float ccSpecularityNoFres;\n"),w.includes("sSpecularLight")&&(C+="vec3 sSpecularLight;\n"),w.includes("sReflection")&&(C+="vec3 sReflection;\n");return this._fsGetBeginCode()+this.varyings+this.varyingDefines+this._fsGetBaseCode()+C+this.frontendDecl+w}generateFragmentShader(t,e,i,n){var a;const s=this.options;this.frontendDecl=t,this.frontendCode=e,this.frontendFunc=i,this.lightingUv=n,s.pass===z?this.fshader=this._fsGetPickPassCode():s.pass===L?this.fshader=this._fsGetDepthPassCode():s.pass===w?this.fshader=this._fsGetPrePassVelocityCode():this.shadowPass?this.fshader=this._fsGetShadowPassCode():s.customFragmentShader?this.fshader=this._fsGetBeginCode()+s.customFragmentShader:this.fshader=this._fsGetLitPassCode(),null==(a=this.handleCompatibility)||a.call(this)}getDefinition(){const t=Q.createDefinition(this.device,{name:"LitShader",attributes:this.attributes,vertexCode:this.vshader,fragmentCode:this.fshader});return this.shaderPassInfo.isForward&&(t.tag=f),t}}export{et as LitShader};