Unity shader学习之渐变纹理

渐变纹理,及使用纹理来存储漫反射光照的结果,这种技术在游戏《军团要塞2》中流行起来,它也是由Valve公司(提出半兰伯特光照技术的公司)提出来的,他们使用这种技术来渲染游戏中具有插画风格的角色。

如使用下图作为渐变纹理:

转载请注明出处:http://www.cnblogs.com/jietian331/p/7133212.html

shader如下:

 1 Shader "Custom/Ramp texture"
 2 {
 3     Properties
 4     {
 5         _RampTex("Ramp texture", 2D) = "white"
 6         _Gloss("Gloss", float) = 20
 7     }
 8 
 9     SubShader
10     {
11         Pass
12         {
13             Tags
14             {
15                 "LightMode" = "ForwardBase"
16             }
17 
18             CGPROGRAM
19             #pragma vertex vert
20             #pragma fragment frag
21 
22             #include "UnityCG.cginc"
23             #include "Lighting.cginc"
24 
25             struct v2f
26             {
27                 float4 pos : SV_POSITION;
28                 float4 worldPos : TEXCOORD0;
29                 float3 worldNormal : TEXCOORD1;
30             };
31 
32             v2f vert(appdata_base v)
33             {
34                 v2f o;
35                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
36                 o.worldPos = mul(unity_ObjectToWorld, v.vertex);
37                 o.worldNormal = normalize(UnityObjectToWorldNormal(v.normal));
38                 return o;
39             }
40 
41             sampler2D _RampTex;
42             float _Gloss;
43 
44             float4 frag(v2f i) : SV_TARGET
45             {
46                 float3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
47                 float3 worldViewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));
48                 
49                 float halfLambert = dot(worldLightDir, i.worldNormal) * 0.5 + 0.5;
50                 float3 diff = _LightColor0.rgb * tex2D(_RampTex, float2(halfLambert, halfLambert));
51 
52                 float3 halfDir = normalize(worldLightDir + worldViewDir);
53                 float3 spec = _LightColor0.rgb * pow(saturate(dot(halfDir, i.worldNormal)), _Gloss);
54 
55                 float3 col = spec + diff + UNITY_LIGHTMODEL_AMBIENT.rgb;
56 
57                 return float4(col.rgb ,1);
58             }
59 
60             ENDCG
61         }
62     }
63 
64     fallback "Diffuse"
65 }
View Code

效果如下:

资源如下:

 https://files.cnblogs.com/files/jietian331/RampTexture.rar

posted @ 2017-07-07 17:12  孤独の巡礼  阅读(3130)  评论(0编辑  收藏  举报