unity屏幕模糊

转载出处:http://blog.youkuaiyun.com/zhaoguanghui2012/article/details/51462284

概述


由于公司手游项目需求,需要一个适合手机平台的模糊效果,同时需要开放一个参数便于调节模糊值。我首先想到的就是ps里面的均值模糊。查资料可以知道均值模糊是一种快速的图像模糊技术,相比与传统的卷积模糊(如高斯模糊),均值模糊可以更加有效率的完成对图像模糊。在unity官方自带imageeffect包也有一个blur的屏幕特效,用的就是均值模糊算法,只不过他只采样了离原像素上下左右模糊半径(Blur Spread)距离的四个像素进行平均处理。然后做迭代(Iterations)处理,即将模糊后的图像再次采样模糊,迭代次数越高越模糊,同时也会产生更多的drawcall,本文的效果就是从这个例子简化而来,使之适合手游项目,并且傻瓜式方便的调节参数。


原理


均值模糊的原理是通过图形滤波器来把一个像素和周围的像素一起求平均值,比如一个三阶的图像滤波器构造其实就是一个3*3的数组(n阶数组中的元素成为滤波器的系数和滤波器的权重,n称为滤波器的阶),相当于把一个像素和周围8个像素相加在一起再除以9求平均值,等于把一个像素和周围的像素搅拌在一起,自然就模糊了。均值滤波器与高斯模糊的滤波器不同的地方,就是采样的像素权重是相等的,因此效果相对而言要比高斯模糊差,但速度却要快一些。本例其实只采样了四个像素求和做平均,然后通过迭代多次采样,实现比较好的模糊效果。


Shader代码实现


shader代码部分相对比较简单,首先需要定义两个内部变量,_MainTex_TexelSize和_BlurOffsets,这两个变量都属于unity的黑魔法,官方文档并没有详细说明,_MainTex_TexelSize的解释可以参考这里,_BlurOffsets这个参数是用来接收从C#脚本里面穿过来的参数,即模糊半径。


[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. half4 _MainTex_TexelSize;  
  2. half4 _BlurOffsets;  

在顶点输入结构体里面定义一个一维四阶数组用来存储uv坐标:


[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. struct v2f {  
  2.     float4 vertex : SV_POSITION;  
  3.     half2 texcoord : TEXCOORD0;  
  4.     half2 taps[4] : TEXCOORD1;   
  5. };  

在vert函数里面将uv坐标进行偏移获得原像素上下左右偏移_BlurOffsets像素,并存储在taps[]数组里面,传给frag函数


[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. v2f vert (appdata_t v)  
  2. {  
  3.     v2f o;  
  4.     o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);  
  5.     o.texcoord = v.texcoord - _BlurOffsets.xy * _MainTex_TexelSize.xy;//将C#脚本传过来的图像偏移回原位置  
  6.     o.taps[0] = o.texcoord + _MainTex_TexelSize * _BlurOffsets.xy;  
  7.     o.taps[1] = o.texcoord - _MainTex_TexelSize * _BlurOffsets.xy;  
  8.     o.taps[2] = o.texcoord + _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);  
  9.     o.taps[3] = o.texcoord - _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);  
  10.     return o;  
  11.       
  12.       
  13. }  

在frag函数使用vert函数传过来的uv坐标数组采样图像然后进行叠加后平均化,以达到模糊效果:


[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. fixed4 frag (v2f i) : SV_Target  
  2. {  
  3.     half4 color = tex2D(_MainTex, i.taps[0]);  
  4.     color += tex2D(_MainTex, i.taps[1]);  
  5.     color += tex2D(_MainTex, i.taps[2]);  
  6.     color += tex2D(_MainTex, i.taps[3]);   
  7.     return color * 0.25;  
  8. }  

Shader完整代码


VF版本代码01 
[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Shader "PengLu/ImageEffect/Unlit/BlurBox" {  
  2.     Properties {  
  3.     _MainTex ("Base (RGB)", 2D) = "white" {}  
  4. }  
  5.   
  6. SubShader {   
  7.     Pass {  
  8.         ZTest Always    ZWrite Off  
  9.   
  10.         CGPROGRAM  
  11.         #pragma vertex vert  
  12.         #pragma fragment frag  
  13.                      
  14.         #include "UnityCG.cginc"  
  15.   
  16.         struct appdata_t {  
  17.             float4 vertex : POSITION;  
  18.             float2 texcoord : TEXCOORD0;  
  19.         };  
  20.   
  21.         struct v2f {  
  22.             float4 vertex : SV_POSITION;  
  23.             half2 texcoord : TEXCOORD0;  
  24.             half2 taps[4] : TEXCOORD1;   
  25.         };  
  26.   
  27.         sampler2D _MainTex;  
  28.         half4 _MainTex_TexelSize;  
  29.         half4 _BlurOffsets;  
  30.           
  31.         v2f vert (appdata_t v)  
  32.         {  
  33.             v2f o;  
  34.             o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);  
  35.             o.texcoord = v.texcoord - _BlurOffsets.xy * _MainTex_TexelSize.xy;  
  36.             o.taps[0] = o.texcoord + _MainTex_TexelSize * _BlurOffsets.xy;  
  37.             o.taps[1] = o.texcoord - _MainTex_TexelSize * _BlurOffsets.xy;  
  38.             o.taps[2] = o.texcoord + _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);  
  39.             o.taps[3] = o.texcoord - _MainTex_TexelSize * _BlurOffsets.xy * half2(1,-1);  
  40.             return o;  
  41.               
  42.               
  43.         }  
  44.           
  45.         fixed4 frag (v2f i) : SV_Target  
  46.         {  
  47.             half4 color = tex2D(_MainTex, i.taps[0]);  
  48.             color += tex2D(_MainTex, i.taps[1]);  
  49.             color += tex2D(_MainTex, i.taps[2]);  
  50.             color += tex2D(_MainTex, i.taps[3]);   
  51.             return color * 0.25;  
  52.         }  
  53.     ENDCG  
  54.     }  
  55. }  
  56. Fallback off  
  57. }  

C#脚本代码


C#脚本相对也比较简单,这个脚本主要负责把抓取屏幕并传递参数给shader进行模糊处理,这个脚本是从官方的简化而来,将迭代的次数固定为2,只留下模糊半径一个参数调节。关键的两个函数需要注意下:


[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Graphics.BlitMultiTap (source, dest, material,  
  2.                        new Vector2(-off, -off),  
  3.                        new Vector2(-off,  off),  
  4.                        new Vector2( off,  off),  
  5.                        new Vector2( off, -off)  
  6.     );  

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. RenderTexture buffer = RenderTexture.GetTemporary(rtW, rtH, 0);  

Graphics.BlitMultiTap函数官方解释在这里  ,大概意思是传递多个位图块给shader进行处理,每个位图块有各自的偏移(由vector[]数组决定)。但实际上我测试发现,这个函数传递的位图块是配合固定管线编程使用的,在5.0以下的blur特效shader代码里有以下代码:上面那个函数生成的四个纹理块一次对应下面四个_MainTex,shader代码里面并没有偏移,都是从Graphics.BlitMultiTap传递过来。

[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. SubShader {  
  2.         Pass {  
  3.             ZTest Always Cull Off ZWrite Off Fog { Mode Off }  
  4.             SetTexture [_MainTex] {constantColor (0,0,0,0.25) combine texture * constant alpha}  
  5.             SetTexture [_MainTex] {constantColor (0,0,0,0.25) combine texture * constant + previous}  
  6.             SetTexture [_MainTex] {constantColor (0,0,0,0.25) combine texture * constant + previous}  
  7.             SetTexture [_MainTex] {constantColor (0,0,0,0.25) combine texture * constant + previous}  
  8.         }  
  9.     }  




而在unity5.0的官方blur shader里面已经将固定管线的相关代码删除,而对vert&frag shader编程,它实际上传递了一个uv坐标偏移值为(off,off)的位图块给shader,并将偏移值传给内置变量_BlurOffsets,我们在相关代码里要重新做偏移,才会有偏移效果。因此Graphics.BlitMultiTap我们可以改成:


[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Graphics.BlitMultiTap (source, dest, material,new Vector2(off, off) );  

RenderTexture.GetTemporary这个函数在这里主要是用来重新设定抓取的屏幕图像的长宽,在本例中我们将长宽设置成原来的8分之1后然后再传递给shader处理,可以是采样计算消耗降低到原来的64分之1,只是因此多消耗一个drawcall。由于还迭代了两次,最后这个屏幕特效需要消耗4个drawcall,当然由于做了个判断,当Blur Size为0时,只消耗1个drallcall,不做模糊处理。


完整C#脚本如下: 
[csharp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using System;  
  4.   
  5. [ExecuteInEditMode]  
  6. [AddComponentMenu ("PengLu/ImageEffect/Blurbox")]  
  7. public class ImageEffect_BlurBox : MonoBehaviour {  
  8.     #region Variables  
  9.     public Shader BlurBoxShader = null;  
  10.     private Material BlurBoxMaterial = null;  
  11.   
  12.     [Range(0.0f, 1.0f)]  
  13.     public float BlurSize = 0.5f;  
  14.  
  15.     #endregion  
  16.  
  17.     #region Properties  
  18.   
  19.     Material material  
  20.     {  
  21.         get  
  22.         {  
  23.             if(BlurBoxMaterial == null)  
  24.             {  
  25.                 BlurBoxMaterial = new Material(BlurBoxShader);  
  26.                 BlurBoxMaterial.hideFlags = HideFlags.HideAndDontSave;    
  27.             }  
  28.             return BlurBoxMaterial;  
  29.         }  
  30.     }  
  31.     #endregion  
  32.     // Use this for initialization  
  33.     void Start () {  
  34.   
  35.         BlurBoxShader = Shader.Find("PengLu/ImageEffect/Unlit/BlurBox");  
  36.           
  37.         // Disable if we don't support image effects  
  38.         if (!SystemInfo.supportsImageEffects)  
  39.         {  
  40.             enabled = false;  
  41.             return;  
  42.         }  
  43.   
  44.         // Disable the image effect if the shader can't  
  45.         // run on the users graphics card  
  46.         if (!BlurBoxShader || !BlurBoxShader.isSupported)  
  47.             enabled = false;  
  48.             return;  
  49.       
  50.     }  
  51.   
  52.     public void FourTapCone (RenderTexture source, RenderTexture dest,int iteration)  
  53.         {  
  54.             float off = BlurSize*iteration+0.5f;  
  55.             Graphics.BlitMultiTap (source, dest, material,  
  56.                                    new Vector2(-off, -off),  
  57.                                    new Vector2(-off,  off),  
  58.                                    new Vector2( off,  off),  
  59.                                    new Vector2( off, -off)  
  60.                 );  
  61.         }  
  62.   
  63.     private void DownSample4x (RenderTexture source, RenderTexture dest)  
  64.         {  
  65.             float off = 1.0f;  
  66.             // Graphics.Blit(source, dest, material);  
  67.             Graphics.BlitMultiTap (source, dest, material,  
  68.                                    new Vector2(off, off),  
  69.                                    new Vector2(-off,  off),  
  70.                                    new Vector2( off,  off),  
  71.                                    new Vector2( off, -off)  
  72.                 );  
  73.         }  
  74.   
  75.     void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)  
  76.     {     
  77.         if(BlurSize != 0 && BlurBoxShader != null){  
  78.   
  79.             int rtW = sourceTexture.width/8;  
  80.             int rtH = sourceTexture.height/8;  
  81.             RenderTexture buffer = RenderTexture.GetTemporary(rtW, rtH, 0);  
  82.   
  83.             DownSample4x (sourceTexture, buffer);  
  84.   
  85.             for(int i = 0; i < 2; i++)  
  86.             {  
  87.                 RenderTexture buffer2 = RenderTexture.GetTemporary(rtW, rtH, 0);  
  88.                 FourTapCone (buffer, buffer2,i);  
  89.                 RenderTexture.ReleaseTemporary(buffer);  
  90.                 buffer = buffer2;  
  91.             }  
  92.             Graphics.Blit(buffer, destTexture);  
  93.   
  94.             RenderTexture.ReleaseTemporary(buffer);  
  95.         }  
  96.   
  97.         else{  
  98.             Graphics.Blit(sourceTexture, destTexture);  
  99.               
  100.         }  
  101.           
  102.           
  103.     }  
  104.       
  105.     // Update is called once per frame  
  106.     void Update () {  
  107.         #if UNITY_EDITOR  
  108.         if (Application.isPlaying!=true)  
  109.         {  
  110.             BlurBoxShader = Shader.Find("PengLu/ImageEffect/Unlit/BlurBox");  
  111.   
  112.         }  
  113.         #endif  
  114.       
  115.     }  
  116.   
  117.      public void OnDisable () {  
  118.         if (BlurBoxMaterial)  
  119.             DestroyImmediate (BlurBoxMaterial);  
  120.     }  
  121. }  

最终模糊特效效果:



 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值