Shader2.0-高斯模糊的實現
阿新 • • 發佈:2018-11-15
要實現高斯模糊,大致的思路是,當某個遊戲物體渲染完成後,將該遊戲物體交給Shader進行二次渲染,從而實現高斯模糊,C#中有一個回撥函式OnRenderImage,這個函式會在渲染完成後呼叫,我們可以在這個函式中呼叫Graphics.Blit方法會把傳進來的圖片與第三個引數中的材質進行二次計算,然後將二次計算的結果賦值給第二個引數。恰好OnRenderImage的第一個引數和第二個引數分別是Graphics.Blit方法的第一個和第二個引數。由於博主語言表達能力不好,還是見程式碼。
1.新建一個 C#指令碼掛在到MainCamera上,程式碼如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraRendener : MonoBehaviour { public Material gaosiMaterial; private void OnRenderImage(RenderTexture source, RenderTexture destination) { Graphics.Blit(source, destination, gaosiMaterial); } }
新建一個材質和一個Shader,將Shader指定給新建的材質,並將材質複製到剛才指令碼的材質變數中,然後開始編寫Shader程式碼:
Shader "Hidden/TestStruct" { Properties { _MainTex ("Texture", 2D) = "white" {} _Amb("Double",Float) = 0.001 //表示模糊的程度 } SubShader { Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _MainTex; float _Amb; struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; }; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.uv; return o; } fixed4 frag (v2f i) : SV_Target { //高斯模糊,原理請自行百度,博主語言表達實在不行 fixed4 col = tex2D(_MainTex, i.uv); fixed4 col1 = tex2D(_MainTex, i.uv + float2(_Amb, 0)); fixed4 col2 = tex2D(_MainTex, i.uv + float2(-_Amb, 0)); fixed4 col3 = tex2D(_MainTex, i.uv + float2(0, _Amb)); fixed4 col4 = tex2D(_MainTex, i.uv + float2(0, -_Amb)); return (col+col1+col2+col3+col4)/5.0; } ENDCG } } }