unity3d Shader镜面高光反射(使用fresenl), bolinPhone是没有物理依据的

来源:互联网 发布:js 深拷贝 循环引用 编辑:程序博客网 时间:2024/06/08 08:10

原文地址:http://www.cnblogs.com/-867259206/p/5657110.html

Unity内置的高光函数

Unity内置了一种高光光照模型——BlinnPhone。
使用方法如下:

Shader "Custom/BlinnPhong"{    Properties     {        _MainTex ("Base (RGB)", 2D) = "white" {}        _MainTint ("Diffuse Tint", Color) = (1,1,1,1)        _SpecColor ("Specular Color", Color) = (1,1,1,1)        _SpecPower ("Specular Power", Range(0,1)) = 0.5    }        SubShader     {        Tags { "RenderType"="Opaque" }        LOD 200                CGPROGRAM        #pragma surface surf BlinnPhong        sampler2D _MainTex;        float _SpecPower;        float4 _MainTint;        struct Input         {            float2 uv_MainTex;        };        void surf (Input IN, inout SurfaceOutput o)         {            half4 c = tex2D (_MainTex, IN.uv_MainTex) * _MainTint;            o.Specular = _SpecPower;            o.Gloss = 1.0;            o.Albedo = c.rgb;            o.Alpha = c.a;        }        ENDCG    }     FallBack "Diffuse"}

使用内置的光照函数就是要在#pragma里声明它。
_SpecColor是Unity内置的一个变量,在Properties里声明是为了可以在Inspector面板里调节它,所以在后面我们没有使用这个变量。它控制高光的颜色。

BlinnPhone是Phone光照模型的改进,要学习这个光照模型先来学习Phone光照模型吧。


Phone光照模型

Phone光照模型就是叫Phone的人发明的光照模型。
代码如下:

Shader "Custom/Phong" {    Properties     {        _MainTint ("Diffuse Tint", Color) = (1,1,1,1)        _MainTex ("Base (RGB)", 2D) = "white" {}        _SpecularColor ("Specular Color", Color) = (1,1,1,1)        _SpecPower ("Specular Power", Range(0.1,30)) = 1    }        SubShader     {        Tags { "RenderType"="Opaque" }        LOD 200                CGPROGRAM        #pragma surface surf Phong                float4 _SpecularColor;        sampler2D _MainTex;        float4 _MainTint;        float _SpecPower;                inline fixed4 LightingPhong (SurfaceOutput s, fixed3 lightDir, half3 viewDir, fixed atten)        {            //Calculate diffuse and the reflection vector            float diff = dot(s.Normal, lightDir);            float3 reflectionVector = normalize((2.0 * s.Normal * diff) - lightDir);                        //Calculate the Phong specular            float spec = pow(max(0,dot(reflectionVector, viewDir)), _SpecPower);            float3 finalSpec = _SpecularColor.rgb * spec;                        //Create final color            fixed4 c;            c.rgb = (s.Albedo * _LightColor0.rgb * diff) + (_LightColor0.rgb * finalSpec);            c.a = 1.0;            return c;        }        struct Input         {            float2 uv_MainTex;        };        void surf (Input IN, inout SurfaceOutput o)         {            half4 c = tex2D (_MainTex, IN.uv_MainTex) * _MainTint;            o.Albedo = c.rgb;            o.Alpha = c.a;        }        ENDCG    }     FallBack "Diffuse"}

Phone光照模型分析

reflectionVector是反射光向量。float3 reflectionVector = normalize((2.0 * s.Normal * diff) - lightDir); 就是由法线、入射光向量求反射光向量的方法。
推导如下图:

后面计算反射向量和观察向量的点积时用max函数是为了背向视线的地方不至于太黑。
最后的颜色就是漫反射颜色加上镜面反射颜色。

BlinnPhone光照模型

BlinnPhone光照模型就是叫Blinn的人改进了Phone光照模型。
在CGIncludes文件夹下Lighting.cginc文件里有BlinnPhone光照函数的定义:

inline fixed4 UnityBlinnPhongLight (SurfaceOutput s, half3 viewDir, UnityLight light){    half3 h = normalize (light.dir + viewDir);        fixed diff = max (0, dot (s.Normal, light.dir));        float nh = max (0, dot (s.Normal, h));    float spec = pow (nh, s.Specular*128.0) * s.Gloss;        fixed4 c;    c.rgb = s.Albedo * light.color * diff + light.color * _SpecColor.rgb * spec;    c.a = s.Alpha;    return c;}

h是半角向量。半角向量就是平分两个向量之间夹角的单位向量。两个向量相加,结果是两个向量构成的平行四边形的对角线,所以半角向量是两个向量相加。
BlinnPhone的改进就是不用反射向量去计算镜面反射,而是用入射光向量和观察向量的半角向量来代替计算。这一方法也是没有物理依据的,只是这样计算计算量更少而且效果差不多甚至更好。如今的着色器十有八九会使用它。
在这里Phone(左)和BlinnPhone(右)的对比:

使用贴图对模型的高光进行遮罩

使用高光贴图技术就是使用贴图来控制高光的颜色和强度。这里用到了自定义的SurfaceOutput,计算方法和Phone模型差不多,只是通过surf函数将高光遮罩贴图的像素信息传给了光照模型:

Shader "Custom/CustomPhone" {    Properties {        _MainTint ("Diffuse Tint", Color) = (1,1,1,1)        _MainTex ("Albedo (RGB)", 2D) = "white" {}        _SpecularColor ("Specular Tint", Color) = (1,1,1,1)        _SpecularMask ("Specular Texture", 2D) = "white"{}        _SpecPower("Specular Power", Range(0.1, 120)) = 3    }    SubShader {        Tags { "RenderType"="Opaque" }        LOD 200                CGPROGRAM        #pragma surface surf CustomPhong        // Use shader model 3.0 target, to get nicer looking lighting        #pragma target 3.0        sampler2D _MainTex;        sampler2D _SpecularMask;        float4 _MainTint;        float4 _SpecularColor;        float _SpecPower;        struct Input {            float2 uv_MainTex;            float2 uv_SpecularMask;        };        struct SurfaceCustomOutput        {            fixed3 Albedo;            fixed3 Normal;            fixed3 Emission;            fixed3 SpecularColor;            half Specular;            fixed Gloss;            fixed Alpha;        };        inline fixed4 LightingCustomPhong(SurfaceCustomOutput s, fixed3 lightDir, half3 viewDir, fixed atten)        {            // Calculate diffuse and the reflection vector            float diff = dot(s.Normal, lightDir);            float3 reflectionVector = normalize(2.0 * s.Normal * diff - lightDir);            // Calculate the Phong specular            float spec = pow(max(0.0f, dot(reflectionVector, viewDir)), _SpecPower) * s.Specular;            float3 finalSpec = s.SpecularColor * spec * _SpecularColor.rgb;            // Create final color            fixed4 c;            c.rgb = (s.Albedo * _LightColor0.rgb * diff) + (_LightColor0.rgb * finalSpec);            c.a = s.Alpha;            return c;        }        void surf(Input IN, inout SurfaceCustomOutput o) {            // Albedo comes from a texture tinted by color            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _MainTint;            float4 specMask = tex2D(_SpecularMask, IN.uv_SpecularMask) * _SpecularColor;            o.Albedo = c.rgb;            o.Specular = specMask.r;            o.SpecularColor = specMask.rgb;            o.Alpha = c.a;        }        ENDCG    }    FallBack "Diffuse"}

金属与软高光

这一节,有点让人怕怕~
我们会用到的几张粗糙贴图:



先上完整代码吧:

Shader "Custom/MetalAndSoftSpec" {    Properties     {        _MainTint ("Diffuse Tint", Color) = (1,1,1,1)        _MainTex ("Base (RGB)", 2D) = "white" {}        _RoughnessTex ("Roughness texture", 2D) = "" {}        _Roughness ("Roughness", Range(0,1)) = 0.5        _SpecularColor ("Specular Color", Color) = (1,1,1,1)        _SpecPower ("Specular Power", Range(0,30)) = 2        _Fresnel ("Fresnel Value", Range(0,1.0)) = 0.05    }        SubShader     {        Tags { "RenderType"="Opaque" }        LOD 200                CGPROGRAM        #pragma surface surf MetallicSoft        #pragma target 3.0        sampler2D _MainTex;        sampler2D _RoughnessTex;        float _Roughness;        float _Fresnel;        float _SpecPower;        float4 _MainTint;        float4 _SpecularColor;                inline fixed4 LightingMetallicSoft (SurfaceOutput s, fixed3 lightDir, half3 viewDir, fixed atten)        {            //Compute simple diffuse and view direction values            float3 halfVector = normalize(lightDir + viewDir);                        float4 c;            //c.rgb = (s.Albedo * _LightColor0.rgb * halfVector);            //return c;            float NdotL = saturate(dot(s.Normal, normalize(lightDir)));            //c.rgb = s.Albedo*_LightColor0.rgb * NdotL;            //return c;            float NdotH_raw = dot(s.Normal, halfVector);            float NdotH = saturate(dot(s.Normal, halfVector));            //c.rgb = s.Albedo*_LightColor0.rgb*NdotH;            //return c;            float NdotV = saturate(dot(s.Normal, normalize(viewDir)));            float VdotH = saturate(dot(halfVector, normalize(viewDir)));            //c.rgb = s.Albedo*_LightColor0.rgb*VdotH;            //return c;                        //Micro facets distribution            float geoEnum = 2.0*NdotH;            float3 G1 = (geoEnum * NdotV)/NdotH;            float3 G2 = (geoEnum * NdotL)/NdotH;            float3 G =  min(1.0f, min(G1, G2));                        //Sample our Spceular look up BRDF            float roughness = tex2D(_RoughnessTex, float2(NdotH_raw * 0.5 + 0.5, _Roughness)).r;                        //Create our custom fresnel value            float fresnel = pow(1.0-VdotH, 5.0);            fresnel *= (1.0 - _Fresnel);            fresnel += _Fresnel;                        //Create the final spec            float3 spec = float3(fresnel * G * roughness * roughness) * _SpecPower;                        //float4 c;            c.rgb = (s.Albedo * _LightColor0.rgb * NdotL)+  (spec * _SpecularColor.rgb) * (atten * 2.0f);            c.a = s.Alpha;            return c;        }        struct Input         {            float2 uv_MainTex;        };        void surf (Input IN, inout SurfaceOutput o)         {            half4 c = tex2D (_MainTex, IN.uv_MainTex) * _MainTint;            o.Albedo = c.rgb;            o.Alpha = c.a;        }        ENDCG    }     FallBack "Diffuse"}

看了有点头晕,没事,听我慢慢说。

  1. _Roughness是粗糙度。用来控制高光的范围。越粗糙的物体高光范围越大,越光滑的物体高光越尖锐。漫反射的物体就是因为太粗糙了,高光范围大到看不见。

  2. _Fresnel是菲涅尔系数。当我们正对着物体时,物体高光就变得很弱,几乎没有,比如正对水面的时候可以看见水底,侧着看的时候就能看见水面的波光。

  3. 让人头晕的就是光照函数了。里面注释掉的语句是我的调试,你们可以一层一层调试看看。(聪明的孩子都自己上机调试去了)

  4. halfVector是半角向量。G是几何衰减系数,描述由于微平面(microfacets)产生的自投影。G和半角之间的代码就是用来求G的。这个算法叫Cook–Torrance。看下Wiki:

    G的求法和代码中的求法是一样的。
    至于这个算法的推导,搜索Cook Torrance可以找到。比如这篇:http://www.twinklingstar.cn/2013/213/torrance-sparrow-and-cook-torrance-light-model/ (我承认,我看了一眼就放弃了)

  5. 后面一句是从粗糙纹理的R通道中获取粗糙度。因为粗糙贴图是黑白的,所以RGB三个通道的值都是相同的。NdotH_raw是原始的半角向量和法线的点积,乘0.5+0.5是为了让它的区间变为[0,1],因为纹理的坐标区间是[0,1],然后用粗糙度作为Y坐标,进行粗糙纹理的采样。

  6. 再后面是计算菲涅尔系数。菲涅尔系数的本质是反映被折射和反射的光通量的比率。这是菲涅尔系数的一个近似求法。它的求法属于物理学的内容,这是近似求法,精度在1%范围内。_Fresnel是我们在面板定义的一个变量。它是入射光接近0时(接近法线)的菲涅尔系数。关于它更详细的介绍,看这篇博文。

  7. 最后的反射变量就是菲涅尔系数乘几何衰减系数乘粗糙度的平方。最后的颜色等于漫反射颜色加镜面反射颜色。

其实Shader的学习是研究生阶段的课程,但是Unity让本科生也可以学一学。


0 0
原创粉丝点击