# 【Shader练习-模糊】

模糊效果的Shader实现练习。

模糊前

Markdown 图片

模糊参数

Markdown 图片

模糊后

Markdown 图片

Shader "Vp/Blur/BlurShader" {
    Properties {
        _MainTexture ("主要纹理",2d) = "white"{}
        _Size ("模糊程度",Range(0.0,5.0)) = 2.0
        _Separation ("散开大小",Range(0.0,0.1)) = 0.01
    }
    SubShader {
        Tags {
            "RenderType"="Opaque"
        }
        Pass {
            Name "FORWARD"
            Tags {
                "LightMode"="ForwardBase"
            }
            
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
            #pragma multi_compile_fwdbase_fullshadows
            #pragma target 3.0

            uniform sampler2D _MainTexture;
            uniform float _Size;
            uniform float _Separation;

            struct VertexInput {
                float4 vertex : POSITION;
                float4 uv : TEXCOORD0;
            };
            struct VertexOutput {
                float4 pos : SV_POSITION;
                float4 uv :TEXCOORD0;
            };
            VertexOutput vert (VertexInput v) {
                VertexOutput o = (VertexOutput)0;
                o.pos = UnityObjectToClipPos( v.vertex );
                o.uv = v.uv;
                return o;
            }
            float4 frag(VertexOutput inp) : COLOR {
                float count = 0.0;
                float4 result = float4(0,0,0,0);
                float4 color = float4(0,0,0,0);
                for (int i = -_Size; i <= _Size; ++i) {
                    for (int j = -_Size; j <= _Size; ++j) {
                        float2 uv2 = (inp.uv + (float2(i,j) * _Separation));
                        color = tex2D(_MainTexture,uv2);
                        result += color;
                        count  += 1.0;
                    }
                }
                result /= count;
                return  result;
            }
            ENDCG
        }
    }
    FallBack "Diffuse"
}