Shader入门精要笔记 - CH7.3_渐变图控制漫反射
左边是使用了前面提到的SpecularPerPixel,中间是没加渐变图时,右边是加了渐变图
高光+渐变图漫反射(RampTex)
Shader "My/Tex/RampTexture" { Properties { _Color("Diffuse Color", Color) = (1, 1, 1, 1) _RampTex("Ramp Tex", 2D) = "white" {} //渐变贴图 _Specular("Specular", Color) = (1, 1, 1, 1) //高光反射颜色 _Gloss("Gloss", Range(8.0, 256)) = 20 //高光区域大小 } SubShader { Tags { "LightMode" = "ForwardBase" } Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "Lighting.cginc" struct appdata { float4 vertex : POSITION; float3 normal : NORMAL; //顶点法线 float2 texcoord : TEXCOORD0; }; struct v2f { float4 vertex : SV_POSITION; float2 uv : TEXCOORD0; float3 worldNormal : TEXCOORD1; float3 worldPos: TEXCOORD2; }; fixed4 _Color; sampler2D _RampTex; float4 _RampTex_ST; fixed4 _Specular; float _Gloss; v2f vert(appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.worldNormal = UnityObjectToWorldNormal(v.normal); o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz; o.uv = TRANSFORM_TEX(v.texcoord, _RampTex); return o; } fixed4 frag(v2f i) : SV_Target { fixed3 worldNormal = normalize(i.worldNormal); //顶点法线(世界空间) fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos)); //指向光源向量(世界空间) fixed3 ambientColor = UNITY_LIGHTMODEL_AMBIENT.xyz; //环境光 fixed halfLambert = 0.5 * dot(worldNormal, worldLightDir) + 0.5; //半兰伯特公式 fixed3 rampDiffuseColor = tex2D(_RampTex, fixed2(halfLambert, halfLambert)).rgb * _Color.rgb; //采样渐变图 fixed3 diffuseColor = _LightColor0.rgb * rampDiffuseColor; fixed3 worldViewDir = normalize(UnityWorldSpaceViewDir(i.worldPos)); //视线方向(顶点到相机) fixed3 halfDir = normalize(worldLightDir + worldViewDir); // blinn模型引入的h向量 fixed3 specularColor = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(worldNormal, halfDir)), _Gloss); // blinn模型高光反射计算公式(更亮, 高光区域更大) return fixed4(ambientColor + diffuseColor + specularColor, 1); } ENDCG } } Fallback "Specular" }