YY一下:为什么这篇文章我这么就才写,是因为大家都用GrabPass取做玻璃效果,其实原理就是多一个特俗pass去渲染。可想而知,其开销也是巨大的,所以我在准备GrabPass的教程的时候,我也准备了另一个制作方式。先来看看GrabPass效果:
因为是抓拍图片渲染贴在玻璃上面,所以我很容易处理扰动效果实现毛玻璃效果;
fixed4 maincolor=tex2D(_MainTex,i.uv); //玻璃自身颜色采样。
fixed4 bump=tex2D(_Bump,i.uv); //玻璃法线贴图纹理采样
fixed2 disstortion=UnpackNormal(bump).rg; //将纹理颜色转化为法线方向;
i.uvgrab.xy+=disstortion*_Magnitude;//对uvgrab进行扰动。
完整代码如下,只是标准,大家可以自由扩展,(再次提示:GrabPass其实开销并不小,使用一定要注意场景应用)
Shader "Unlit/GrabShader_Glass"
{
//1:把对象下已经绘制的内容抓拍到纹理当中;
//2:使用法线贴图替换纹理中的像素;
//3:把失真的像素渲染到屏幕上;
//特俗Pass:GrabPass ,把当前内容渲染到纹理上,(而不是渲染到屏幕上)且保证玻璃不会被绘制。
Properties
{
_Color("COlor",color)=(1,1,1,1)
_MainTex ("Texture", 2D) = "white" {}
_Bump ("normal",2D)="bump"{}
_Magnitude("Magnitude",Range(0,1))=0.5 }
SubShader
{
Tags {
//渲染队列的顺序,最后渲染透明;
"Queue"="Transparent"
"IgnoreProjector"="true"
"RenderType"="Opaque"
}
//关闭深度计算可以解决模型显示破面问题
ZWrite Off
Lighting Off
Cull Off
Blend one Zero
//在对玻璃前置渲染时,把整个场景(除去玻璃)渲染到_GrabTexture纹理上
//注意:GrabPass其实开销巨大,相当于一个新的pass;
GrabPass {"_GrabTexture"}
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
half4 vertex : POSITION;
fixed4 color:COLOR;
fixed2 uv : TEXCOORD0;
};
struct v2f
{
fixed4 color:COLOR;
fixed2 uv:TEXCOORD0; //MainTex 纹理坐标
fixed4 uvgrab : TEXCOORD1;//Bump 的纹理坐标;
UNITY_FOG_COORDS(2)
half4 vertex : POSITION;
};
sampler2D _GrabTexture;//存入拍摄的GrabPass纹理;
sampler2D _MainTex;
sampler2D _Bump;
fixed _Magnitude;
fixed4 _Color;
//计算每个顶点像素的属性(位置,纹理坐标等等)
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
// ComputeGrabScreenPos传入投影空间中的坐标,
o.uvgrab = ComputeGrabScreenPos(o.vertex);
o.color= v.color;
o.uv=v.uv;
// o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
//光栅化处理,顶点到片元的属性计算,得到每个片元的颜色值。
fixed4 frag (v2f i) : SV_Target
{
fixed4 maincolor=tex2D(_MainTex,i.uv); //玻璃自身颜色采样。
fixed4 bump=tex2D(_Bump,i.uv); //玻璃法线贴图纹理采样
fixed2 disstortion=UnpackNormal(bump).rg; //将纹理颜色转化为法线方向;
i.uvgrab.xy+=disstortion*_Magnitude;//对uvgrab进行扰动。
// sample the texture
fixed4 col = tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(i.uvgrab)); //玻璃背后的颜色计算
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col*maincolor*_Color; //合成最终效果
}
ENDCG
}
}
}
下一篇移动端低消耗高性能玻璃shader实现:http://t.csdnimg.cn/bfvGY