原文链接:
http://www.onevcat.com/2013/08/shader-tutorial-2/
http://blog.sina.com.cn/s/blog_89d90b7c0102va4m.html
1.积雪效果
Shader "hongGe/Normal" { Properties { _MainTex ("Base (RGB)", 2D) = "white" {} _NormalMap("NormalMap",2D) = "Bump"{} _SnowLevel ("Snow Level", Range(0,1) ) = 0 _SnowColor ("Snow Color", Color) = (1,1,1,1) _SnowDirection ("Snow Direction", Vector) = (0,1,0) } SubShader { Pass { Tags { "LightMode"="ForwardBase" } CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" uniform sampler2D _MainTex; uniform sampler2D _NormalMap; uniform float _SnowLevel; uniform float4 _SnowColor; uniform float4 _SnowDirection; uniform float4 _LightColor0; struct VertexOutput { float4 pos:SV_POSITION; float2 uv:TEXCOORD0; float3 lightDir:TEXCOORD1; float3x3 World2Tangent:TEXCOORD2; }; VertexOutput vert(appdata_tan v) { VertexOutput o; o.pos = mul(UNITY_MATRIX_MVP,v.vertex); o.uv = v.texcoord.xy; o.lightDir = WorldSpaceLightDir(v.vertex); //rotation是模型空间到切线空间 TANGENT_SPACE_ROTATION; o.World2Tangent = mul(rotation,_World2Object); return o; } float4 frag(VertexOutput input):COLOR { float3 tangentNormal = UnpackNormal(tex2D(_NormalMap, input.uv)); float3 worldNormal = mul(tangentNormal,input.World2Tangent); if(dot(worldNormal, _SnowDirection) > lerp(1,-1,_SnowLevel)) { return _SnowColor; } else { float4 texColor = tex2D(_MainTex,input.uv); float3 diffuseReflection = texColor.rgb * _LightColor0.rgb * max(0,dot(worldNormal,input.lightDir)); return float4(diffuseReflection,1); } } ENDCG } } FallBack "Diffuse" }
2.捕捉纹理(整个屏幕的纹理)
Shader "hongGe/GrabTexture" { Properties { } SubShader { // 在所有不透明对象之后绘制自己,更加靠近屏幕 Tags{"Queue"="Transparent"} // 通道1:捕捉屏幕内容放到_GrabTexture纹理中 GrabPass{} // 通道2:设置材质 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _GrabTexture; struct VertexOutput { float4 pos:SV_POSITION; float2 uv:TEXCOORD0; }; VertexOutput vert(appdata_base v) { VertexOutput o; o.pos = mul(UNITY_MATRIX_MVP,v.vertex); o.uv = v.texcoord.xy; return o; } float4 frag(VertexOutput input):COLOR { //可能要根据情况对uv坐标进行一些修改 half4 texCol = tex2D(_GrabTexture,float2(input.uv.x , 1-input.uv.y)); return texCol; } ENDCG } } FallBack "Diffuse" }
前:
后:
3.捕捉纹理(被遮挡的纹理)
Shader "hongGe/GrabTexture" { Properties { } SubShader { // 在所有不透明对象之后绘制自己,更加靠近屏幕 Tags{"Queue"="Transparent"} // 通道1:捕捉屏幕内容放到_GrabTexture纹理中 GrabPass{} // 通道2:设置材质 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _GrabTexture; struct VertexOutput { float4 pos:SV_POSITION; float2 uv:TEXCOORD0; }; VertexOutput vert(appdata_base v) { VertexOutput o; o.pos = mul(UNITY_MATRIX_MVP,v.vertex); float2 screenUV = ComputeGrabScreenPos(o.pos);//计算该模型顶点在屏幕坐标的纹理信息 o.uv = screenUV; return o; } float4 frag(VertexOutput input):COLOR { half4 texCol = tex2D(_GrabTexture,input.uv); return 1 - texCol; } ENDCG } } FallBack "Diffuse" }