Unity3D shader(18)——水的折射与反射

有任何shader的问题,直接qq254033230
水的折射与反射原理其实差不多,只是一个用ComputeGrabScreenPos(o.pos)来取得贴图,一个用ComputeScreenPos(o.pos)来取得贴图。另外还需要两个脚本,一个是工具类的脚本,一个是得到反射贴图的脚本。
这里直接放上核心源码:

Shader "GameCore/Mobile/Water/Diffuse" 
{
    Properties {                
        _BaseColor("BaseColor",color)=(1,1,1,1)
        _MainTex("Texture",2D)="white"{}
        _ReflectionTex("ReflectionTex",2D)=""{}
        _Bias("Bias",range(0,1))=0
        _Scale("Scale",range(0,1))=0
        _Pow("Pow",range(0,5))=1
        }
        SubShader {
        Tags {"RenderType"="Opaque" "Queue"="transparent"}

                LOD 100
                grabpass{}
                Pass {
                         CGPROGRAM
                        #pragma vertex vert
                        #pragma fragment frag
                        #include "UnityCG.cginc"
                        #include "Lighting.cginc"


              float4 _BaseColor;
              sampler2D _MainTex;
              float4 _MainTex_ST;
              sampler2D _GrabTexture;
              sampler2D _ReflectionTex;
              float _Bias,_Scale,_Pow;


                struct v2f {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                float4 proj:TEXCOORD1;
                float4 refl:TEXCOORD2;
                float3 L:TEXCOORD3;
                float3 V:TEXCOORD4;
              };



    v2f vert(appdata_tan v){

         v2f o;

         o.pos=UnityObjectToClipPos(v.vertex);
         o.uv=TRANSFORM_TEX(v.texcoord.xy,_MainTex);
         o.proj=ComputeGrabScreenPos(o.pos);
         o.refl=ComputeScreenPos(o.pos);
         o.L=ObjSpaceLightDir(v.vertex);
         o.V=ObjSpaceViewDir(v.vertex);

         TANGENT_SPACE_ROTATION;
         o.L=mul(rotation,o.L);
         o.V=mul(rotation,o.V);

         return o;
        }

        float4 frag(v2f IN):SV_Target{
        float4 col1=tex2D(_MainTex,IN.uv+float2(_Time.x,0));  
        float4 col2=tex2D(_MainTex,float2(1-IN.uv.y,IN.uv.x)+float2(_Time.x,0)); //水的波动
        float4 col=(col1+col2)/2;

        float3 N=normalize(UnpackNormal(col));  //法向量
        float off_xy=dot(N,float3(0,1,0));      //法向量和竖直方向向量的点积

         IN.proj.xy+=off_xy*0.1;                //顶点加上偏移量
         float4 gcol=tex2Dproj(_GrabTexture,IN.proj);  //折射效果

          float diff=max(0,dot(N,normalize(IN.L)));  //法线与灯光的点积
          float3 H=normalize(normalize(IN.L)+normalize(IN.V));
          float spec=pow(max(0,dot(N,H)),128);   //高光效果

           float4 diffCol=diff*_BaseColor;       
           diffCol.rgb+=spec*_LightColor0.rgb;
           IN.refl.xy+=off_xy*0.3;
           float4 reflcol=tex2Dproj(_ReflectionTex,IN.refl);  
           float4 fresnel=_Bias+_Scale*pow(1+dot(N,-normalize(IN.V)),_Pow);
           float4 finalColor=lerp(gcol,reflcol,fresnel);
           //fixed4 finalColor=lerp(fresnel,gcol,diffCol);
           return finalColor;   


        }
                        ENDCG
                }
        }
}

效果:
Unity3D shader(18)——水的折射与反射_第1张图片

其中:工具类脚本CodeTool.cs

using System.Collections;
using System;
using UnityEngine;

/// 
/// 工具类
/// 
public static class CoreTool
{
    #region Config配置
    /// 
    /// 验证当前文件是否为配置文件
    /// 
    /// 文件路径
    /// 
    public static bool IsConfig(string filePath)
    {
        return true;
    }
    #endregion

    #region Camera
    /// 
    /// 将源摄像机状态克隆到目标相机
    /// 
    /// 源相机
    /// 目标相机
    public static void CloneCameraModes(Camera src, Camera dest)
    {
        if (dest == null)
            return;
        // set camera to clear the same way as current camera
        dest.clearFlags = src.clearFlags;
        dest.backgroundColor = src.backgroundColor;
        if (src.clearFlags == CameraClearFlags.Skybox)
        {
            Skybox sky = src.GetComponent(typeof(Skybox)) as Skybox;
            Skybox mysky = dest.GetComponent(typeof(Skybox)) as Skybox;
            if (!sky || !sky.material)
            {
                mysky.enabled = false;
            }
            else
            {
                mysky.enabled = true;
                mysky.material = sky.material;
            }
        }
        // update other values to match current camera.
        // even if we are supplying custom camera&projection matrices,
        // some of values are used elsewhere (e.g. skybox uses far plane)
        dest.depth = src.depth;
        dest.farClipPlane = src.farClipPlane;
        dest.nearClipPlane = src.nearClipPlane;
        dest.orthographic = src.orthographic;
        dest.fieldOfView = src.fieldOfView;
        dest.aspect = src.aspect;
        dest.orthographicSize = src.orthographicSize;
    }

    /// 
    /// 计算反射矩阵
    /// 
    /// 原始矩阵
    /// 反射平面
    /// 反射矩阵
    public static Matrix4x4 CalculateReflectionMatrix(Matrix4x4 reflectionMat, Vector4 plane)
    {
        reflectionMat.m00 = (1F - 2F * plane[0] * plane[0]);
        reflectionMat.m01 = (-2F * plane[0] * plane[1]);
        reflectionMat.m02 = (-2F * plane[0] * plane[2]);
        reflectionMat.m03 = (-2F * plane[3] * plane[0]);

        reflectionMat.m10 = (-2F * plane[1] * plane[0]);
        reflectionMat.m11 = (1F - 2F * plane[1] * plane[1]);
        reflectionMat.m12 = (-2F * plane[1] * plane[2]);
        reflectionMat.m13 = (-2F * plane[3] * plane[1]);

        reflectionMat.m20 = (-2F * plane[2] * plane[0]);
        reflectionMat.m21 = (-2F * plane[2] * plane[1]);
        reflectionMat.m22 = (1F - 2F * plane[2] * plane[2]);
        reflectionMat.m23 = (-2F * plane[3] * plane[2]);

        reflectionMat.m30 = 0F;
        reflectionMat.m31 = 0F;
        reflectionMat.m32 = 0F;
        reflectionMat.m33 = 1F;
        return reflectionMat;
    }

    /// 
    /// 计算指定平面在摄像机中的空间位置
    /// 
    /// 摄像机
    /// 平面上的点
    /// 平面法线
    /// 1:平面正面,-1:平面反面
    /// 平面法线位置偏移量
    /// 
    public static Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign,float clipPlaneOffset)
    {        
        Vector3 offsetPos = pos + normal * clipPlaneOffset;
        Matrix4x4 m = cam.worldToCameraMatrix;
        Vector3 cpos = m.MultiplyPoint(offsetPos);
        Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign;
        return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal));
    }

    /// 
    /// 由剪裁面计算投影倾斜矩阵
    /// 
    /// 投影矩阵
    /// 剪裁面
    /// 剪裁平面(-1:平面下面,1:平面上面)
    public static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projection, Vector4 clipPlane,float sideSign)
    {
        Vector4 q = projection.inverse * new Vector4(
            sgn(clipPlane.x),
            sgn(clipPlane.y),
            1.0f,
            1.0f
        );
        Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q)));
        // third row = clip plane - fourth row
        projection[2] = c.x + Mathf.Sign(sideSign)*projection[3];
        projection[6] = c.y + Mathf.Sign(sideSign) * projection[7];
        projection[10] = c.z + Mathf.Sign(sideSign) * projection[11];
        projection[14] = c.w + Mathf.Sign(sideSign) * projection[15];
        return projection;
    }

    private static float sgn(float a)
    {
        if (a > 0.0f) return 1.0f;
        if (a < 0.0f) return -1.0f;
        return 0.0f;
    }

    /// 
    /// 由水平、垂直距离修改倾斜矩阵
    /// 
    /// 倾斜矩阵
    /// 水平方向
    /// 垂直方向
    /// 修改后的倾斜矩阵
    public static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projMatrix, float horizObl, float vertObl)
    {
        Matrix4x4 mat = projMatrix;
        mat[0, 2] = horizObl;
        mat[1, 2] = vertObl;
        return mat;
    }
    #endregion

    #region Shader Matrix4x4
    /// 
    /// tex2DProj到tex2D的uv纹理转换矩阵
    /// 在shader中,
    /// vert=>o.posProj = mul(_ProjMatrix, v.vertex);
    /// frag=>tex2D(_RefractionTex,float2(i.posProj) / i.posProj.w)
    /// 
    /// 要显示纹理的对象
    /// 当前观察的摄像机
    /// 返回转换矩阵
    public static Matrix4x4 UV_Tex2DProj2Tex2D(Transform transform,Camera cam)
    {
        Matrix4x4 scaleOffset = Matrix4x4.TRS(
            new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f));
        Vector3 scale = transform.lossyScale;
        Matrix4x4 _ProjMatrix = transform.localToWorldMatrix * Matrix4x4.Scale(new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z));
        _ProjMatrix = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * _ProjMatrix;
        return _ProjMatrix;
    }
    #endregion
}

得到反射贴图的脚本:ReflectionEffect.cs

using UnityEngine;
using System.Collections;
using System;

/// 
/// 反射效果
/// 
[AddComponentMenu("GameCore/SpecialEffect/Reflection")]
[ExecuteInEditMode]
public class ReflectionEffect : MonoBehaviour
{
    public Camera MainCamera;
    public bool DisablePixelLights = true;
    public int TextureSize = 512;
    public float ClipPlaneOffset = 0;
    public LayerMask ReflectLayers = -1;

    private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table
    private RenderTexture m_ReflectionTexture = null;
    private int m_OldReflectionTextureSize = 0;

    private static bool s_InsideRendering = false;

    // This is called when it's known that the object will be rendered by some
    // camera. We render reflections and do other updates here.
    // Because the script executes in edit mode, reflections for the scene view
    // camera will just work!
    public void OnWillRenderObject()
    {
        if (!enabled || !GetComponent() || !GetComponent().sharedMaterial || !GetComponent().enabled)
            return;

        Camera cam = MainCamera;
        if (!cam)
            return;

        // Safeguard from recursive reflections.        
        if (s_InsideRendering)
            return;
        s_InsideRendering = true;

        Camera reflectionCamera;
        CreateMirrorObjects(cam, out reflectionCamera);

        // find out the reflection plane: position and normal in world space
        Vector3 pos = transform.position;
        Vector3 normal = transform.up;


        // Optionally disable pixel lights for reflection
        int oldPixelLightCount = QualitySettings.pixelLightCount;
        if (DisablePixelLights)
            QualitySettings.pixelLightCount = 0;

        CoreTool.CloneCameraModes(cam, reflectionCamera);

        // Render reflection
        // Reflect camera around reflection plane
        float d = -Vector3.Dot(normal, pos) - ClipPlaneOffset;
        Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);


        Matrix4x4 reflection = CoreTool.CalculateReflectionMatrix(Matrix4x4.zero, reflectionPlane);




        Vector3 oldpos = cam.transform.position;
        Vector3 newpos = reflection.MultiplyPoint(oldpos);
        reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;



        // Setup oblique projection matrix so that near plane is our reflection
        // plane. This way we clip everything below/above it for free.
        Vector4 clipPlane = CoreTool.CameraSpacePlane(reflectionCamera, pos, normal, 1.0f, ClipPlaneOffset);

        Matrix4x4 projection = cam.projectionMatrix;

        projection = CoreTool.CalculateObliqueMatrix(projection, clipPlane,1);

        reflectionCamera.projectionMatrix = projection;

        reflectionCamera.cullingMask = ~(1 << 4) & ReflectLayers.value; // never render water layer
        reflectionCamera.targetTexture = m_ReflectionTexture;

        GL.SetRevertBackfacing(true);
        reflectionCamera.transform.position = newpos;
        Vector3 euler = cam.transform.eulerAngles;
        reflectionCamera.transform.eulerAngles = new Vector3(0, euler.y, euler.z);
        reflectionCamera.Render();
        reflectionCamera.transform.position = oldpos;
        GL.SetRevertBackfacing(false);
        Material[] materials = GetComponent().sharedMaterials;
        foreach (Material mat in materials)
        {
            if (mat.HasProperty("_ReflectionTex"))
                mat.SetTexture("_ReflectionTex", m_ReflectionTexture);
        }

        // Set matrix on the shader that transforms UVs from object space into screen
        // space. We want to just project reflection texture on screen.
        Matrix4x4 scaleOffset = Matrix4x4.TRS(
            new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f));
        Vector3 scale = transform.lossyScale;
        Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale(new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z));
        mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
        foreach (Material mat in materials)
        {
            mat.SetMatrix("_ProjMatrix", mtx);
        }
        // Restore pixel light count
        if (DisablePixelLights)
            QualitySettings.pixelLightCount = oldPixelLightCount;

        s_InsideRendering = false;
    }


    // Cleanup all the objects we possibly have created
    void OnDisable()
    {
        if (m_ReflectionTexture)
        {
            DestroyImmediate(m_ReflectionTexture);
            m_ReflectionTexture = null;
        }
        foreach (DictionaryEntry kvp in m_ReflectionCameras)
            DestroyImmediate(((Camera)kvp.Value).gameObject);
        m_ReflectionCameras.Clear();
    }

    // On-demand create any objects we need
    private void CreateMirrorObjects(Camera currentCamera, out Camera reflectionCamera)
    {
        reflectionCamera = null;

        // Reflection render texture
        if (!m_ReflectionTexture || m_OldReflectionTextureSize != TextureSize)
        {
            if (m_ReflectionTexture)
                DestroyImmediate(m_ReflectionTexture);
            m_ReflectionTexture = new RenderTexture(TextureSize, TextureSize,0);
            m_ReflectionTexture.name = "__MirrorReflection" + GetInstanceID();
            m_ReflectionTexture.isPowerOfTwo = true;
            m_ReflectionTexture.hideFlags = HideFlags.DontSave;
            m_ReflectionTexture.antiAliasing = 4;
            m_ReflectionTexture.anisoLevel = 0;
            m_OldReflectionTextureSize = TextureSize;
        }

        // Camera for reflection
        reflectionCamera = m_ReflectionCameras[currentCamera] as Camera;
        if (!reflectionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
        {
            GameObject go = new GameObject("Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));
            reflectionCamera = go.GetComponent();
            reflectionCamera.enabled = false;
            reflectionCamera.transform.position = transform.position;
            reflectionCamera.transform.rotation = transform.rotation;
            reflectionCamera.gameObject.AddComponent();
            go.hideFlags = HideFlags.HideAndDontSave;
            m_ReflectionCameras[currentCamera] = reflectionCamera;
        }
    }
}

当然,以上的水的波纹可以按照需求调整。
有一篇博客写得挺好的,那篇博客把波浪和水深的渐变加进去了,效果相当棒。如果用那篇文章的内容加上本篇的内容,基本上就把水的各种技术问题解决了。
http://blog.csdn.net/mobilebbki399/article/details/50493117

最后的效果如下图:有波纹、有反射、折射、有浪花、有水深颜色渐变

Unity3D shader(18)——水的折射与反射_第2张图片

你可能感兴趣的:(Unity3D,shader)