Unity3D Shader编程】之十一 深入理解Unity5中的Standard Shader(三)&屏幕像素化特效的实现

本系列文章由@浅墨_毛星云 出品,转载请注明出处。   
文章链接:  http://blog.csdn.net/poem_qianmo/article/details/50095705
作者:毛星云(浅墨)    微博:http://weibo.com/u/1723155442
本文工程使用的Unity3D版本:   5.2.1 


 
概要:续接上文,本文进一步讲解与分析了上文未讲完的Unity5中Standard Shader正向基础渲染通道源码的片段着色实现部分,以及对屏幕像素化后期特效进行了实现。
 
同样需要声明的是。本文中对Stardard Shader源码的一些分析,全是浅墨自己通过对Unity Shader内建源码的理解,以及Google之后理解与分析而来。如有解释不妥当之处,还请各位及时指出。
 

依然是附上一组本文配套工程的运行截图之后,便开始我们的正文。


傍晚的野外(with 屏幕像素化特效):
 


傍晚的野外(原始场景):



图依然是贴这两张。文章末尾有更多的运行截图,并提供了源工程的下载。先放出可运行的exe下载,如下:

【可运行的本文配套exe游戏场景请点击这里下载】
 
提示:在此游戏场景中按F键可以开关屏幕特效。


 

 
一、关于BRDF(双向反射分布函数)
 

本次源码剖析有涉及BRDF的相关内容,这边简单提一下。
双向反射分布函数(Bidirectional ReflectanceDistribution Function,BRDF)用来定义给定入射方向上的辐射照度(irradiance)如何影响给定出射方向上的辐射率(radiance)。更笼统地说,它描述了入射光线经过某个表面反射后如何在各个出射方向上分布——这可以是从理想镜面反射到漫反射、各向同性(isotropic)或者各向异性(anisotropic)的各种反射。
 
BRDF作为图形学中比较常见的一个知识点,这边暂时不多讲,因为随便拿一本图形学相关的书都可以看到他的身影。这边给出一些参考的链接,大家有需要可以深入了解:
 
1. 如何正确理解 BRDF (双向反射分布函数)? - 计算机 - 知乎
2.图形学理论知识:BRDF 双向反射分布函数
3. An Introduction to BRDF-based Lighting –Nvidia


 



 

二、续Standard Shader中正向基础渲染通道源码分析


 


此部分接上文《【浅墨Unity3D Shader编程】之十 深入理解Unity5中的Standard Shader(二)&屏幕油画特效的实现》的第二部分“Standard Shader中正向基础渲染通道源码分析“。

上文中分析了Standard Shader中正向基础渲染通道的源码,刚好分析完了顶点着色函数vertForwardBase,本文中将对片段着色函数fragForwardBase 进行说明。分析完之后,也就结束了这一系列长得稍微有些离谱的Standard Shader正向基础渲染通道的源码分析。
 

OK,开始吧,先上注释好的片段着色函数fragForwardBase的代码,位于UnityStandardCore.cginc中:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //----------------------------------------【fragForwardBase函数】-------------------------------------------  
  2. //  用途:正向渲染基础通道的片段着色函数  
  3. //  输入:VertexOutputForwardBase结构体  
  4. //  输出:一个half4类型的颜色值  
  5. //------------------------------------------------------------------------------------------------------------------  
  6. half4 fragForwardBase (VertexOutputForwardBase i) : SV_Target  
  7. {  
  8.     //定义并初始化类型为FragmentCommonData的变量s  
  9.     FRAGMENT_SETUP(s)  
  10.     //若定义了UNITY_OPTIMIZE_TEXCUBELOD,则由输入的顶点参数来设置反射光方向向量  
  11. #if UNITY_OPTIMIZE_TEXCUBELOD  
  12.     s.reflUVW       = i.reflUVW;  
  13. #endif  
  14.   
  15.     //设置主光照  
  16.     UnityLight mainLight = MainLight (s.normalWorld);  
  17.   
  18.     //设置阴影的衰减系数  
  19.     half atten = SHADOW_ATTENUATION(i);  
  20.   
  21.     //计算全局光照  
  22.     half occlusion = Occlusion(i.tex.xy);  
  23.     UnityGI gi = FragmentGI (s, occlusion, i.ambientOrLightmapUV, atten, mainLight);  
  24.   
  25.     //加上BRDF-基于物理的光照  
  26.     half4 c = UNITY_BRDF_PBS (s.diffColor, s.specColor, s.oneMinusReflectivity, s.oneMinusRoughness, s.normalWorld, -s.eyeVec, gi.light, gi.indirect);  
  27.     //加上BRDF-全局光照  
  28.     c.rgb += UNITY_BRDF_GI (s.diffColor, s.specColor, s.oneMinusReflectivity, s.oneMinusRoughness, s.normalWorld, -s.eyeVec, occlusion, gi);  
  29.     //加上自发光  
  30.     c.rgb += Emission(i.tex.xy);  
  31.   
  32.     //设置雾效  
  33.     UNITY_APPLY_FOG(i.fogCoord, c.rgb);  
  34.   
  35.     //返回最终的颜色  
  36.     return OutputForward (c, s.alpha);  
  37. }  
依然是老规矩,把上面代码中新接触到的相关内容进行下分条讲解。





1. FRAGMENT_SETUP(x)宏

FRAGMENT_SETUP(x)宏定义于UnityStandardCore.cginc头文件中,其作用其实就是用FragmentSetup函数初始化括号中的x变量。
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. #define FRAGMENT_SETUP(x) FragmentCommonData x = \  
  2.     FragmentSetup(i.tex, i.eyeVec, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndParallax, IN_WORLDPOS(i));  

调用此宏,也就是表示写了如下的代码,定义了一个x变量:
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. FragmentCommonData x =FragmentSetup(i.tex, i.eyeVec, IN_VIEWDIR4PARALLAX(i), i.tangentToWorldAndParallax, IN_WORLDPOS(i));  


其中FragmentSetup函数也定义于UnityStandardCore.cginc头文件中,用于填充一个FragmentCommonData结构体并于返回值中返回,也就是进行片段函数相关参数的初始化,相关代码如下:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //函数FragmentSetup:填充一个FragmentCommonData结构体并于返回值中返回,进行片段函数相关参数的初始化  
  2. inline FragmentCommonData FragmentSetup (float4 i_tex, half3 i_eyeVec, half3 i_viewDirForParallax, half4 tangentToWorld[3], half3 i_posWorld)  
  3. {  
  4.     i_tex = Parallax(i_tex, i_viewDirForParallax);  
  5.   
  6.     half alpha = Alpha(i_tex.xy);  
  7.     #if defined(_ALPHATEST_ON)  
  8.         clip (alpha - _Cutoff);  
  9.     #endif  
  10.   
  11.     FragmentCommonData o = UNITY_SETUP_BRDF_INPUT (i_tex);  
  12.     o.normalWorld = PerPixelWorldNormal(i_tex, tangentToWorld);  
  13.     o.eyeVec = NormalizePerPixelNormal(i_eyeVec);  
  14.     o.posWorld = i_posWorld;  
  15.   
  16.     // NOTE: shader relies on pre-multiply alpha-blend (_SrcBlend = One, _DstBlend = OneMinusSrcAlpha)  
  17.     o.diffColor = PreMultiplyAlpha (o.diffColor, alpha, o.oneMinusReflectivity, /*out*/ o.alpha);  
  18.     return o;  
  19. }  
其中的FragmentCommonData结构体也是定义于UnityStandardCore.cginc头文件中:
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //FragmentCommonData结构体:存放片段着色常用变量  
  2. struct FragmentCommonData  
  3. {  
  4.     half3 diffColor, specColor;//漫反射颜色;镜面反射颜色  
  5.     // Note: oneMinusRoughness & oneMinusReflectivity for optimization purposes, mostly for DX9 SM2.0 level.  
  6.     // Most of the math is being done on these (1-x) values, and that saves a few precious ALU slots.  
  7.     half oneMinusReflectivity, oneMinusRoughness;//1减去反射率;1减去粗糙度  
  8.     half3 normalWorld, eyeVec, posWorld;//世界空间中的法线向量坐标;视角向量坐标;在世界坐标中的位置坐标  
  9.     half alpha;//透明度  
  10.   
  11. #if UNITY_OPTIMIZE_TEXCUBELOD || UNITY_STANDARD_SIMPLE  
  12.     half3 reflUVW;//反射率的UVW  
  13. #endif  
  14.   
  15. #if UNITY_STANDARD_SIMPLE  
  16.     half3 tangentSpaceNormal;//切线空间中的法线向量  
  17. #endif  
  18. };  



 

2. MainLight函数



MainLight函数定义于UnityStandardCore.cginc头文件中,用途是实例化一个UnityLight结构体对象,并进行相应的填充,其返回值作为主光源。相关代码如下:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //  用途:该函数为主光照函数  
  2. //  说明:实例化一个UnityLight结构体对象,并进行相应的填充  
  3. /* 
  4. //注:UnityLight结构体定义于UnityLightingCommon.cginc文件中,原型如下: 
  5. struct UnityLight 
  6. { 
  7. half3 color; 
  8. half3 dir; 
  9. half  ndotl; 
  10. }; 
  11. */  
  12.   
  13. //------------------------------------【函数3】MainLight函数-----------------------------------------  
  14. //  用途:该函数为主光照函数  
  15. //  说明:实例化一个UnityLight结构体对象,并进行相应的填充  
  16. //---------------------------------------------------------------------------------------------------------  
  17. UnityLight MainLight (half3 normalWorld)  
  18. {  
  19.     //【1】实例化一个UnityLight的对象  
  20.     UnityLight l;  
  21.   
  22.     //【2】填充UnityLight的各个参数  
  23.     //若光照贴图选项为关,使用Unity内置变量赋值  
  24.     #ifdef LIGHTMAP_OFF  
  25.         //获取光源的颜色  
  26.         l.color = _LightColor0.rgb;   
  27.         //获取光源的方向  
  28.         l.dir = _WorldSpaceLightPos0.xyz;  
  29.         //获取法线与光源方向的点乘的积  
  30.         l.ndotl = LambertTerm (normalWorld, l.dir);  
  31.   
  32.     //光照贴图选项为开,将各项值设为0  
  33.     #else  
  34.         l.color = half3(0.f, 0.f, 0.f);  
  35.         l.ndotl  = 0.f;  
  36.         l.dir = half3(0.f, 0.f, 0.f);  
  37.     #endif  
  38.   
  39.     //返回赋值完成的UnityLight结构体对象  
  40.     return l;  
  41. }  


 

3. SHADOW_ATTENUATION宏



SHADOW_ATTENUATION宏相关的代码位于AutoLight.cginc头文件中,用于实现阴影渲染相关的辅助工作,代码如下:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. // ----------------  
  2. //  阴影相关工具代码 || Shadow helpers  
  3. // ----------------  
  4.   
  5. // ---- 屏幕空间阴影 || Screen space shadows  
  6. #if defined (SHADOWS_SCREEN)  
  7. ……  
  8. #define SHADOW_ATTENUATION(a) unitySampleShadow(a._ShadowCoord)  
  9. #endif  
  10.   
  11.   
  12. // ----聚光灯光源阴影 || Spot light shadows  
  13. #if defined (SHADOWS_DEPTH) && defined (SPOT)  
  14.     #define SHADOW_COORDS(idx1) unityShadowCoord4 _ShadowCoord : TEXCOORD##idx1;  
  15.     #define TRANSFER_SHADOW(a) a._ShadowCoord = mul (unity_World2Shadow[0], mul(_Object2World,v.vertex));  
  16.     #define SHADOW_ATTENUATION(a) UnitySampleShadowmap(a._ShadowCoord)  
  17. #endif  
  18.   
  19.   
  20. // ----点光源阴影 ||  Point light shadows  
  21. #if defined (SHADOWS_CUBE)  
  22.     #define SHADOW_COORDS(idx1) unityShadowCoord3 _ShadowCoord : TEXCOORD##idx1;  
  23.     #define TRANSFER_SHADOW(a) a._ShadowCoord = mul(_Object2World, v.vertex).xyz - _LightPositionRange.xyz;  
  24.     #define SHADOW_ATTENUATION(a) UnitySampleShadowmap(a._ShadowCoord)  
  25. #endif  
  26.   
  27. // ---- 关闭阴影 || Shadows off  
  28. #if !defined (SHADOWS_SCREEN) && !defined (SHADOWS_DEPTH) && !defined (SHADOWS_CUBE)  
  29.     #define SHADOW_COORDS(idx1)  
  30.     #define TRANSFER_SHADOW(a)  
  31.     #define SHADOW_ATTENUATION(a) 1.0  
  32. #endif  

可以发现,SHADOW_ATTENUATION(a)宏除了在关闭阴影的状态是等于1以外,其他几种情况都是等价于UnitySampleShadowmap(a._ShadowCoord)函数的调用。而这里的UnitySampleShadowmap函数,定于于UnityShadowLibrary.cginc函数中。实现代码如下。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //------------------------------【UnitySampleShadowmap函数】---------------------------------  
  2. // 用途:采样阴影贴图,得到阴影衰减值  
  3. // 输入参数: float3型的阴影向量坐标vec  
  4. // 返回值:阴影衰减值  
  5. //-------------------------------------------------------------------------------------------------------  
  6. inline half UnitySampleShadowmap (float3 vec)  
  7. {  
  8.     float mydist = length(vec) * _LightPositionRange.w;  
  9.     mydist *= 0.97; // bias  
  10.   
  11.     #if defined (SHADOWS_SOFT)  
  12.         float z = 1.0/128.0;  
  13.         float4 shadowVals;  
  14.         shadowVals.x = SampleCubeDistance (vec+float3( z, z, z));  
  15.         shadowVals.y = SampleCubeDistance (vec+float3(-z,-z, z));  
  16.         shadowVals.z = SampleCubeDistance (vec+float3(-z, z,-z));  
  17.         shadowVals.w = SampleCubeDistance (vec+float3( z,-z,-z));  
  18.         half4 shadows = (shadowVals < mydist.xxxx) ? _LightShadowData.rrrr : 1.0f;  
  19.         return dot(shadows,0.25);  
  20.     #else  
  21.         float dist = SampleCubeDistance (vec);  
  22.         return dist < mydist ? _LightShadowData.r : 1.0;  
  23.     #endif  
  24. }  



 

4. Occlusion函数


Occlusion函数用于进行全局光照的第一步。其输入参数为一个float2型的纹理坐标,而其half型的返回值将作为FragmentGI函数的一个输入参数。Occlusion函数的原型如下:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. half Occlusion(float2 uv)  
  2. {  
  3. #if (SHADER_TARGET < 30)  
  4.     // SM20: instruction count limitation  
  5.     // SM20: simpler occlusion  
  6.     return tex2D(_OcclusionMap, uv).g;  
  7. #else  
  8.     half occ = tex2D(_OcclusionMap, uv).g;  
  9.     return LerpOneTo (occ, _OcclusionStrength);  
  10. #endif  
  11. }  

其中的LerpOneTo函数很简单,用于线性插值,输入两个值b和t,返回1+(b-1)*t,具体定义如下:
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. half LerpOneTo(half b, half t)  
  2. {  
  3.     half oneMinusT = 1 - t;  
  4.     return oneMinusT + b * t;  
  5. }  



5. UnityGI结构体
 

UnityGI结构体是Unity中存放全局光照光源信息的结构体,定义于UnityLightingCommon.cginc头文件中,如下。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //全局光照结构体  
  2. struct UnityGI  
  3. {  
  4.     UnityLight light;//定义第一个光源参数结构体,表示第一个光源  
  5.     //若定义了DIRLIGHTMAP_SEPARATE(单独的方向光源光照贴图)  
  6.     #ifdef DIRLIGHTMAP_SEPARATE  
  7.         //若定义了LIGHTMAP_ON(打开光照贴图)  
  8.         #ifdef LIGHTMAP_ON  
  9.             UnityLight light2;//定义第二个光源参数结构体,表示第二个光源  
  10.         #endif  
  11.         //若定义了DYNAMICLIGHTMAP_ON(打开动态光照贴图)  
  12.         #ifdef DYNAMICLIGHTMAP_ON  
  13.             UnityLight light3;//定义第三个光源参数结构体,表示第三个光源  
  14.         #endif  
  15.     #endif  
  16.     UnityIndirect indirect;//Unity中间接光源参数的结构体  
  17. };  

其中包含了UnityLight结构体和UnityIndirect结构体,其中UnityLight结构体是Unity Shader中最基本的光照结构体,而UnityIndirect是Unity中存放间接光源信息的结构体。它们两者也定义于UnityLightingCommon.cginc头文件中,代码如下。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //Unity中光源参数的结构体  
  2. struct UnityLight  
  3. {  
  4.     half3 color;//光源颜色  
  5.     half3 dir;//光源方向  
  6.     half  ndotl; //入射光方向和当前表面法线方向的点积  
  7. };  
  8.   
  9. //Unity中间接光源参数的结构体  
  10. struct UnityIndirect  
  11. {  
  12.     half3 diffuse;//漫反射颜色  
  13.     half3 specular;//镜面反射颜色  
  14. };  




 
6. FragmentGI函数


FragmentGI函数是片段着色部分全局光照的处理函数,定义于UnityStandardCore.cginc头文件中。相关代码如下:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //函数:片段着色部分全局光照的处理函数  
  2. inline UnityGI FragmentGI (FragmentCommonData s, half occlusion, half4 i_ambientOrLightmapUV, half atten, UnityLight light, bool reflections)  
  3. {  
  4.     //【1】实例化一个UnityGIInput的对象  
  5.     UnityGIInput d;  
  6.     //【2】填充此UnityGIInput对象的各个值  
  7.     d.light = light;  
  8.     d.worldPos = s.posWorld;  
  9.     d.worldViewDir = -s.eyeVec;  
  10.     d.atten = atten;  
  11.     #if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)  
  12.         d.ambient = 0;  
  13.         d.lightmapUV = i_ambientOrLightmapUV;  
  14.     #else  
  15.         d.ambient = i_ambientOrLightmapUV.rgb;  
  16.         d.lightmapUV = 0;  
  17.     #endif  
  18.     d.boxMax[0] = unity_SpecCube0_BoxMax;  
  19.     d.boxMin[0] = unity_SpecCube0_BoxMin;  
  20.     d.probePosition[0] = unity_SpecCube0_ProbePosition;  
  21.     d.probeHDR[0] = unity_SpecCube0_HDR;  
  22.   
  23.     d.boxMax[1] = unity_SpecCube1_BoxMax;  
  24.     d.boxMin[1] = unity_SpecCube1_BoxMin;  
  25.     d.probePosition[1] = unity_SpecCube1_ProbePosition;  
  26.     d.probeHDR[1] = unity_SpecCube1_HDR;  
  27.   
  28.     //【3】根据填充好的UnityGIInput结构体对象,调用一下UnityGlobalIllumination函数  
  29.     if(reflections)  
  30.     {  
  31.         Unity_GlossyEnvironmentData g;  
  32.         g.roughness     = 1 - s.oneMinusRoughness;  
  33.     #if UNITY_OPTIMIZE_TEXCUBELOD || UNITY_STANDARD_SIMPLE  
  34.         g.reflUVW       = s.reflUVW;  
  35.     #else  
  36.         g.reflUVW       = reflect(s.eyeVec, s.normalWorld);  
  37.     #endif  
  38.   
  39.         return UnityGlobalIllumination (d, occlusion, s.normalWorld, g);  
  40.     }  
  41.     else  
  42.     {  
  43.         return UnityGlobalIllumination (d, occlusion, s.normalWorld);  
  44.     }  
  45. }  
  46.   
  47. inline UnityGI FragmentGI (FragmentCommonData s, half occlusion, half4 i_ambientOrLightmapUV, half atten, UnityLight light)  
  48. {  
  49.     return FragmentGI(s, occlusion, i_ambientOrLightmapUV, atten, light, true);  
  50. }  


其中的UnityGIInput结构体定义了全局光照所需要的一些函数,定义为如下:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //全局光照的输入参数结构体  
  2. struct UnityGIInput   
  3. {  
  4.     UnityLight light; // 像素光源,由引擎准备并传输过来 || pixel light, sent from the engine  
  5.   
  6.     float3 worldPos;//世界空间中的位置坐标  
  7.     half3 worldViewDir;//世界空间中的视角方向向量坐标  
  8.     half atten;//衰减值  
  9.     half3 ambient;//环境光颜色  
  10.     half4 lightmapUV; //光照贴图的UV坐标,其中 取.xy = static lightmapUV(静态光照贴图的UV) , .zw = dynamic lightmap UV(动态光照贴图的UV)  
  11.   
  12.     float4 boxMax[2];//box最大值  
  13.     float4 boxMin[2];//box最小值  
  14.     float4 probePosition[2];//光照探针的位置  
  15.     float4 probeHDR[2];//光照探针的高动态范围图像(High-Dynamic Range)  
  16. };  

UnityGIInput 中还包含了UnityLight结构体,其定义和代码实现上文刚刚已经有提到过。

FragmentGI函数最终利用了UnityGlobalIllumination函数,其定义于UnityGlobalIllumination.cginc头文件中,实现如下。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. inline UnityGI UnityGlobalIllumination (UnityGIInput data, half occlusion, half3 normalWorld)  
  2. {  
  3.     return UnityGI_Base(data, occlusion, normalWorld);  
  4. }  


FragmentGI 函数就是嵌套了一层UnityGI_Base函数,那我们继续溯源,找到UnityGI_Base函数的定义,也是位于UnityGlobalIllumination.cginc头文件中:
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //UnityGI_Base函数:Unity的全局光照Base版  
  2. inline UnityGI UnityGI_Base(UnityGIInput data, half occlusion, half3 normalWorld)  
  3. {  
  4.     //【1】实例化一个UnityGI类型的结构体  
  5.     UnityGI o_gi;  
  6.     //【2】重置此UnityGI的结构体  
  7.     ResetUnityGI(o_gi);  
  8.   
  9.     //【3】开始逐个填充参数  
  10.     #if !defined(LIGHTMAP_ON)  
  11.         o_gi.light = data.light;  
  12.         o_gi.light.color *= data.atten;  
  13.     #endif  
  14.   
  15.   
  16.     #if UNITY_SHOULD_SAMPLE_SH  
  17.         #if UNITY_SAMPLE_FULL_SH_PER_PIXEL  
  18.             half3 sh = ShadeSH9(half4(normalWorld, 1.0));  
  19.         #elif (SHADER_TARGET >= 30) && !UNITY_STANDARD_SIMPLE  
  20.             half3 sh = data.ambient + ShadeSH12Order(half4(normalWorld, 1.0));  
  21.         #else  
  22.             half3 sh = data.ambient;  
  23.         #endif  
  24.   
  25.         o_gi.indirect.diffuse = sh;  
  26.     #endif  
  27.   
  28.   
  29.     #if defined(LIGHTMAP_ON)  
  30.         // Baked lightmaps  
  31.         fixed4 bakedColorTex = UNITY_SAMPLE_TEX2D(unity_Lightmap, data.lightmapUV.xy);  
  32.         half3 bakedColor = DecodeLightmap(bakedColorTex);  
  33.   
  34.         #ifdef DIRLIGHTMAP_OFF  
  35.             o_gi.indirect.diffuse = bakedColor;  
  36.   
  37.             #ifdef SHADOWS_SCREEN  
  38.                 o_gi.indirect.diffuse = MixLightmapWithRealtimeAttenuation (o_gi.indirect.diffuse, data.atten, bakedColorTex);  
  39.             #endif // SHADOWS_SCREEN  
  40.   
  41.         #elif DIRLIGHTMAP_COMBINED  
  42.             fixed4 bakedDirTex = UNITY_SAMPLE_TEX2D_SAMPLER (unity_LightmapInd, unity_Lightmap, data.lightmapUV.xy);  
  43.             o_gi.indirect.diffuse = DecodeDirectionalLightmap (bakedColor, bakedDirTex, normalWorld);  
  44.   
  45.             #ifdef SHADOWS_SCREEN  
  46.                 o_gi.indirect.diffuse = MixLightmapWithRealtimeAttenuation (o_gi.indirect.diffuse, data.atten, bakedColorTex);  
  47.             #endif // SHADOWS_SCREEN  
  48.   
  49.         #elif DIRLIGHTMAP_SEPARATE  
  50.             // Left halves of both intensity and direction lightmaps store direct light; right halves - indirect.  
  51.   
  52.             // Direct  
  53.             fixed4 bakedDirTex = UNITY_SAMPLE_TEX2D_SAMPLER(unity_LightmapInd, unity_Lightmap, data.lightmapUV.xy);  
  54.             o_gi.indirect.diffuse = DecodeDirectionalSpecularLightmap (bakedColor, bakedDirTex, normalWorld, false, 0, o_gi.light);  
  55.   
  56.             // Indirect  
  57.             half2 uvIndirect = data.lightmapUV.xy + half2(0.5, 0);  
  58.             bakedColor = DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, uvIndirect));  
  59.             bakedDirTex = UNITY_SAMPLE_TEX2D_SAMPLER(unity_LightmapInd, unity_Lightmap, uvIndirect);  
  60.             o_gi.indirect.diffuse += DecodeDirectionalSpecularLightmap (bakedColor, bakedDirTex, normalWorld, false, 0, o_gi.light2);  
  61.         #endif  
  62.     #endif  
  63.   
  64.     #ifdef DYNAMICLIGHTMAP_ON  
  65.         // Dynamic lightmaps  
  66.         fixed4 realtimeColorTex = UNITY_SAMPLE_TEX2D(unity_DynamicLightmap, data.lightmapUV.zw);  
  67.         half3 realtimeColor = DecodeRealtimeLightmap (realtimeColorTex);  
  68.   
  69.         #ifdef DIRLIGHTMAP_OFF  
  70.             o_gi.indirect.diffuse += realtimeColor;  
  71.   
  72.         #elif DIRLIGHTMAP_COMBINED  
  73.             half4 realtimeDirTex = UNITY_SAMPLE_TEX2D_SAMPLER(unity_DynamicDirectionality, unity_DynamicLightmap, data.lightmapUV.zw);  
  74.             o_gi.indirect.diffuse += DecodeDirectionalLightmap (realtimeColor, realtimeDirTex, normalWorld);  
  75.   
  76.         #elif DIRLIGHTMAP_SEPARATE  
  77.             half4 realtimeDirTex = UNITY_SAMPLE_TEX2D_SAMPLER(unity_DynamicDirectionality, unity_DynamicLightmap, data.lightmapUV.zw);  
  78.             half4 realtimeNormalTex = UNITY_SAMPLE_TEX2D_SAMPLER(unity_DynamicNormal, unity_DynamicLightmap, data.lightmapUV.zw);  
  79.             o_gi.indirect.diffuse += DecodeDirectionalSpecularLightmap (realtimeColor, realtimeDirTex, normalWorld, true, realtimeNormalTex, o_gi.light3);  
  80.         #endif  
  81.     #endif  
  82.   
  83.     o_gi.indirect.diffuse *= occlusion;  
  84.   
  85.     //【4】返回此UnityGI类型的结构体  
  86.     return o_gi;  
  87. }  
不难发现,此FragmentGI函数的实现,也就是实例化一个UnityGIInput结构体对象,然后依次填充了此结构体对象的每个各个参数,最后调用一下基于UnityGI_Base函数的UnityGlobalIllumination函数而已。

 



7. UNITY_BRDF_PBS宏


首先,这边有一段宏,定义于UnityPBSLighting.cginc头文件中,根据不同的情况,将UNITY_BRDF_PBS宏定义为不同版本的UNITY_BRDF_PBS宏——是BRDF3_Unity_PBS、BRDF2_Unity_PBS还是BRDF1_Unity_PBS。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //-------------------------------------------------------------------------------------  
  2. // 默认使用BRDF || Default BRDF to use:  
  3. #if !defined (UNITY_BRDF_PBS) // 允许显式地在自定义着色器中重写BRDF的实现细节 || allow to explicitly override BRDF in custom shader  
  4.     //满足着色目标模型的版本小于Shader Model 3.0,或者是PlayStation 2平台  
  5.     #if (SHADER_TARGET < 30) || defined(SHADER_API_PSP2)  
  6.         // 为小于SM3.0的着色模型回退为低保真度的BRDF版本 || Fallback to low fidelity one for pre-SM3.0  
  7.         #define UNITY_BRDF_PBS BRDF3_Unity_PBS  
  8.     #elif defined(SHADER_API_MOBILE)  
  9.         // 为移动平台简化的BRDF版本 || Somewhat simplified for mobile  
  10.         #define UNITY_BRDF_PBS BRDF2_Unity_PBS  
  11.     #else  
  12.         //最高特效的SM3、PC平台或者游戏主机平台的BRDF版本 || Full quality for SM3+ PC / consoles  
  13.         #define UNITY_BRDF_PBS BRDF1_Unity_PBS  
  14.     #endif  
  15. #endif  
三种情况下,BRDF3_Unity_PBS、BRDF2_Unity_PBS、 BRDF1_Unity_PBS三个函数的参数和返回值都一样,区别仅仅是内部的实现。在这边,以BRDF1_Unity_PBS为例,讲一下参数值的含义。
 
half4 BRDF1_Unity_PBS (half3 diffColor,half3 specColor, half oneMinusReflectivity, half oneMinusRoughness,half3 normal,half3 viewDir,UnityLight light, UnityIndirect gi)
 
第一个参数,half3型的diffColor,表示漫反射颜色的值。
第二个参数,half3型的specColor,表示镜面反射颜色值。
第三个参数,half型的oneMinusReflectivity,表示1减去反射率的值。
第四个参数,half型的oneMinusRoughness,表示1减去粗糙度的值。
第五次参数,half3型的normal,表示法线的方向。
第六个参数,half3型的viewDir,表示视线的方向。

第七个参数,UnityLight型的light,表示Unity中光源参数的结构体,包含half3型的光源颜色color,half3型的光源方向dir,half型的入射光方向和当前表面法线方向的点乘的积ndotl。上文有贴出过其实现代码,都几次提到了,这边就再贴一下。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. struct UnityLight  
  2. {  
  3.     half3 color;//光源颜色  
  4.     half3 dir;//光源方向  
  5.     half  ndotl; //入射光方向和当前表面法线方向的点积  
  6. };  
第八个参数,UnityIndirect类型的gi ,一个包含了half3型的漫反射颜色diffuse和half3型的镜面反射颜色specular的光线反射结构体, 表示间接光照信息
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. struct UnityIndirect  
  2. {  
  3.     half3 diffuse;//漫反射颜色  
  4.     half3 specular;//镜面反射颜色  
  5. };  

下面将三种版本的函数分别贴出来,它们都定义于UnityStandardBRDF.cginc头文件中。


 
7.1 BRDF1_Unity_PBS


[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //最高特效的SM3、PC平台或者游戏主机平台的BRDF版本 || Full quality for SM3+ PC / consoles  
  2. //-------------------------------------------------------------------------------------  
  3.   
  4. // Note: BRDF entry points use oneMinusRoughness (aka "smoothness") and oneMinusReflectivity for optimization  
  5. // purposes, mostly for DX9 SM2.0 level. Most of the math is being done on these (1-x) values, and that saves  
  6. // a few precious ALU slots.  
  7.   
  8.   
  9. // Main Physically Based BRDF  
  10. // Derived from Disney work and based on Torrance-Sparrow micro-facet model  
  11. //  
  12. //   BRDF = kD / pi + kS * (D * V * F) / 4  
  13. //   I = BRDF * NdotL  
  14. //  
  15. // * NDF (depending on UNITY_BRDF_GGX):  
  16. //  a) Normalized BlinnPhong  
  17. //  b) GGX  
  18. // * Smith for Visiblity term  
  19. // * Schlick approximation for Fresnel  
  20. half4 BRDF1_Unity_PBS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness,  
  21.     half3 normal, half3 viewDir,  
  22.     UnityLight light, UnityIndirect gi)  
  23. {  
  24.     half roughness = 1-oneMinusRoughness;  
  25.     half3 halfDir = Unity_SafeNormalize (light.dir + viewDir);  
  26.   
  27.     half nl = light.ndotl;  
  28.     half nh = BlinnTerm (normal, halfDir);  
  29.     half nv = DotClamped (normal, viewDir);  
  30.     half lv = DotClamped (light.dir, viewDir);  
  31.     half lh = DotClamped (light.dir, halfDir);  
  32.   
  33. #if UNITY_BRDF_GGX  
  34.     half V = SmithGGXVisibilityTerm (nl, nv, roughness);  
  35.     half D = GGXTerm (nh, roughness);  
  36. #else  
  37.     half V = SmithBeckmannVisibilityTerm (nl, nv, roughness);  
  38.     half D = NDFBlinnPhongNormalizedTerm (nh, RoughnessToSpecPower (roughness));  
  39. #endif  
  40.   
  41.     half nlPow5 = Pow5 (1-nl);  
  42.     half nvPow5 = Pow5 (1-nv);  
  43.     half Fd90 = 0.5 + 2 * lh * lh * roughness;  
  44.     half disneyDiffuse = (1 + (Fd90-1) * nlPow5) * (1 + (Fd90-1) * nvPow5);  
  45.       
  46.     // HACK: theoretically we should divide by Pi diffuseTerm and not multiply specularTerm!  
  47.     // BUT 1) that will make shader look significantly darker than Legacy ones  
  48.     // and 2) on engine side "Non-important" lights have to be divided by Pi to in cases when they are injected into ambient SH  
  49.     // NOTE: multiplication by Pi is part of single constant together with 1/4 now  
  50.   
  51.     half specularTerm = max(0, (V * D * nl) * unity_LightGammaCorrectionConsts_PIDiv4);// Torrance-Sparrow model, Fresnel is applied later (for optimization reasons)  
  52.     half diffuseTerm = disneyDiffuse * nl;  
  53.       
  54.     half grazingTerm = saturate(oneMinusRoughness + (1-oneMinusReflectivity));  
  55.     half3 color =   diffColor * (gi.diffuse + light.color * diffuseTerm)  
  56.                     + specularTerm * light.color * FresnelTerm (specColor, lh)  
  57.                     + gi.specular * FresnelLerp (specColor, grazingTerm, nv);  
  58.   
  59.     return half4(color, 1);  
  60. }  


7.2 BRDF2_Unity_PBS
12

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. // 为移动平台简化的BRDF版本 || Somewhat simplified for mobile  
  2. // Based on Minimalist CookTorrance BRDF  
  3. // Implementation is slightly different from original derivation: http://www.thetenthplanet.de/archives/255  
  4. //  
  5. // * BlinnPhong as NDF  
  6. // * Modified Kelemen and Szirmay-Kalos for Visibility term  
  7. // * Fresnel approximated with 1/LdotH  
  8. half4 BRDF2_Unity_PBS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness,  
  9.     half3 normal, half3 viewDir,  
  10.     UnityLight light, UnityIndirect gi)  
  11. {  
  12.     half3 halfDir = Unity_SafeNormalize (light.dir + viewDir);  
  13.   
  14.     half nl = light.ndotl;  
  15.     half nh = BlinnTerm (normal, halfDir);  
  16.     half nv = DotClamped (normal, viewDir);  
  17.     half lh = DotClamped (light.dir, halfDir);  
  18.   
  19.     half roughness = 1-oneMinusRoughness;  
  20.     half specularPower = RoughnessToSpecPower (roughness);  
  21.     // Modified with approximate Visibility function that takes roughness into account  
  22.     // Original ((n+1)*N.H^n) / (8*Pi * L.H^3) didn't take into account roughness   
  23.     // and produced extremely bright specular at grazing angles  
  24.   
  25.     // HACK: theoretically we should divide by Pi diffuseTerm and not multiply specularTerm!  
  26.     // BUT 1) that will make shader look significantly darker than Legacy ones  
  27.     // and 2) on engine side "Non-important" lights have to be divided by Pi to in cases when they are injected into ambient SH  
  28.     // NOTE: multiplication by Pi is cancelled with Pi in denominator  
  29.   
  30.     half invV = lh * lh * oneMinusRoughness + roughness * roughness; // approx ModifiedKelemenVisibilityTerm(lh, 1-oneMinusRoughness);  
  31.     half invF = lh;  
  32.     half specular = ((specularPower + 1) * pow (nh, specularPower)) / (unity_LightGammaCorrectionConsts_8 * invV * invF + 1e-4h); // @TODO: might still need saturate(nl*specular) on Adreno/Mali  
  33.   
  34.     // Prevent FP16 overflow on mobiles  
  35. #if SHADER_API_GLES || SHADER_API_GLES3  
  36.     specular = clamp(specular, 0.0, 100.0);  
  37. #endif  
  38.   
  39.     half grazingTerm = saturate(oneMinusRoughness + (1-oneMinusReflectivity));  
  40.     half3 color =   (diffColor + specular * specColor) * light.color * nl  
  41.                     + gi.diffuse * diffColor  
  42.                     + gi.specular * FresnelLerpFast (specColor, grazingTerm, nv);  
  43.   
  44.     return half4(color, 1);  
  45. }  


 
7.3 BRDF3_Unity_PBS

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. // 为小于SM3.0的着色模型回退为低保真度的BRDF版本 || Fallback to low fidelity one for pre-SM3.0  
  2. // Old school, not microfacet based Modified Normalized Blinn-Phong BRDF  
  3. // Implementation uses Lookup texture for performance  
  4. //  
  5. // * Normalized BlinnPhong in RDF form  
  6. // * Implicit Visibility term  
  7. // * No Fresnel term  
  8. //  
  9. // TODO: specular is too weak in Linear rendering mode  
  10. half4 BRDF3_Unity_PBS (half3 diffColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness,  
  11.     half3 normal, half3 viewDir,  
  12.     UnityLight light, UnityIndirect gi)  
  13. {  
  14.     half3 reflDir = reflect (viewDir, normal);  
  15.   
  16.     half nl = light.ndotl;  
  17.     half nv = DotClamped (normal, viewDir);  
  18.   
  19.     // Vectorize Pow4 to save instructions  
  20.     half2 rlPow4AndFresnelTerm = Pow4 (half2(dot(reflDir, light.dir), 1-nv));  // use R.L instead of N.H to save couple of instructions  
  21.     half rlPow4 = rlPow4AndFresnelTerm.x; // power exponent must match kHorizontalWarpExp in NHxRoughness() function in GeneratedTextures.cpp  
  22.     half fresnelTerm = rlPow4AndFresnelTerm.y;  
  23.   
  24.     half grazingTerm = saturate(oneMinusRoughness + (1-oneMinusReflectivity));  
  25.   
  26.     half3 color = BRDF3_Direct(diffColor, specColor, rlPow4, oneMinusRoughness);  
  27.     color *= light.color * nl;  
  28.     color += BRDF3_Indirect(diffColor, specColor, gi, grazingTerm, fresnelTerm);  
  29.   
  30.     return half4(color, 1);  
  31. }  


BRDF1_Unity_PBS函数的实现部分用到了最多的变量,最终表现效果最好,主要用于Shader Model 3.0、PC平台或者游戏主机平台。BRDF2_Unity_PBS简化了一部分计算,主要用于移动平台,而BRDF3_Unity_PBS是为Shader Model 小于3.0的着色模型提供基本版的BRDF,实现细节最为简陋。


 



8. UNITY_BRDF_GI宏



UNITY_BRDF_GI宏位于UnityPBSLighting.cginc头文件中,相关代码如下。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //-------------------------------------------------------------------------------------  
  2. // 从间接的方向光照贴图中进行BRDF(双向反射分布函数)的光照提取 || BRDF for lights extracted from *indirect* directional lightmaps (baked and realtime).  
  3. // 使用UNITY_BRDF_PBS从方向光源烘焙方向光照贴图, || Baked directional lightmap with *direct* light uses UNITY_BRDF_PBS.  
  4. // 若想得到更好的效果,可以使用BRDF1_Unity_PBS || For better quality change to BRDF1_Unity_PBS.  
  5. // SM2.0中的非方向光照贴图|| No directional lightmaps in SM2.0.  
  6.   
  7. //若没有定义UNITY_BRDF_PBS_LIGHTMAP_INDIRECT宏  
  8. #if !defined(UNITY_BRDF_PBS_LIGHTMAP_INDIRECT)  
  9.     //定义UNITY_BRDF_PBS_LIGHTMAP_INDIRECT = BRDF2_Unity_PBS  
  10.     #define UNITY_BRDF_PBS_LIGHTMAP_INDIRECT BRDF2_Unity_PBS  
  11. #endif  
  12. //若没有定义UNITY_BRDF_GI宏  
  13. #if !defined (UNITY_BRDF_GI)  
  14.     //定义UNITY_BRDF_GI = BRDF_Unity_Indirect  
  15.     #define UNITY_BRDF_GI BRDF_Unity_Indirect  
  16. #endif  

上面这段代码中关于UNITY_BRDF_GI宏的地方,就是说若没有定义UNITY_BRDF_GI宏,就定义一个UNITY_BRDF_GI宏等价于BRDF_Unity_Indirect。这边的BRDF_Unity_Indirect是一个函数名,就紧紧跟在上面这段宏代码的后面:
 
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //间接光照的BRDF  
  2. inline half3 BRDF_Unity_Indirect (half3 baseColor, half3 specColor, half oneMinusReflectivity, half oneMinusRoughness, half3 normal, half3 viewDir, half occlusion, UnityGI gi)  
  3. {  
  4.     half3 c = 0;  
  5.     #if defined(DIRLIGHTMAP_SEPARATE)  
  6.         gi.indirect.diffuse = 0;  
  7.         gi.indirect.specular = 0;  
  8.   
  9.         #ifdef LIGHTMAP_ON  
  10.             c += UNITY_BRDF_PBS_LIGHTMAP_INDIRECT (baseColor, specColor, oneMinusReflectivity, oneMinusRoughness, normal, viewDir, gi.light2, gi.indirect).rgb * occlusion;  
  11.         #endif  
  12.         #ifdef DYNAMICLIGHTMAP_ON  
  13.             c += UNITY_BRDF_PBS_LIGHTMAP_INDIRECT (baseColor, specColor, oneMinusReflectivity, oneMinusRoughness, normal, viewDir, gi.light3, gi.indirect).rgb * occlusion;  
  14.         #endif  
  15.     #endif  
  16.     return c;  
  17. }  

关于此段代码,BRDF_Unity_Indirect 函数的核心部分其实就是在调用UNITY_BRDF_PBS_LIGHTMAP_INDIRECT,而上文的宏有交代过,UNITY_BRDF_PBS_LIGHTMAP_INDIRECT宏等价于 BRDF2_Unity_PBS。而BRDF2_Unity_PBS函数,其定义于UnityStandardBRDF.cginc中,是为移动平台简化的BRDF版本,这个上文刚刚提到过,这边就不多交代。
 

 


 
9.Emission函数


Emission函数定于于UnityStandardInput.cginc头文件中,根据指定的自发光光照贴图,利用tex2D函数,对输入的纹理进行光照贴图的采样,相关代码如下:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //---------------------------------------【Emission函数】-----------------------------------------  
  2. // 用途:根据指定的自发光光照贴图,利用tex2D函数,对输入的纹理进行光照贴图的采样  
  3. // 输入参数:float2型的纹理坐标  
  4. // 输出参数:经过将自发光纹理和输入纹理进行tex2D采样得到的half3型的自发光颜色  
  5. //-----------------------------------------------------------------------------------------------  
  6. half3 Emission(float2 uv)  
  7. {  
  8. #ifndef _EMISSION  
  9.     return 0;  
  10. #else  
  11.     return tex2D(_EmissionMap, uv).rgb * _EmissionColor.rgb;  
  12. #endif  
  13. }  

其中用于采样的自发光贴图对应的函数定义于UnityStandardInput.cginc头文件的一开始部分。
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. sampler2D   _EmissionMap;  

这边这句代码其实是相当于在CGPROGRAM中的顶点和片段着色函数之前,对这个变量进行声明,以便于CG语言块中使用的时候,能识别到他的含义。 因为在Standard.shader源码的一开始,Properties块也就是属性值声明部分,对其进行了属性的声明:
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //自发光纹理图  
  2. _EmissionMap("Emission", 2D) = "white" {}  


 
 
10.UNITY_APPLY_FOG宏
 


UNITY_APPLY_FOG宏相关的一些代码用于雾效的启用与否的辅助工作,定义于UnityCG.cginc头文件中,这边贴出注释好的代码即可。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //UNITY_FOG_LERP_COLOR宏的定义  
  2. #define UNITY_FOG_LERP_COLOR(col,fogCol,fogFac) col.rgb = lerp((fogCol).rgb, (col).rgb, saturate(fogFac))  
  3.   
  4. //【1】若已经定义了FOG_LINEAR、FOG_EXP、FOG_EXP2宏三者至少之一,便可以进行到此#if实现部分  
  5. #if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)  
  6.     //【1-1】若满足着色目标模型的版本小于Shader Model 3.0,或者定义了SHADER_API_MOBILE宏,便可以进行到此#if实现部分  
  7.     #if (SHADER_TARGET < 30) || defined(SHADER_API_MOBILE)  
  8.         //移动平台和Shader Model 2.0:已经计算了每顶点的雾效因子,所以插一下值就可以了 ||mobile or SM2.0: fog factor was already calculated per-vertex, so just lerp the color  
  9.         //定义 UNITY_APPLY_FOG_COLOR(coord,col,fogCol) 等价于UNITY_FOG_LERP_COLOR(col,fogCol,coord)  
  10.     #define UNITY_APPLY_FOG_COLOR(coord,col,fogCol) UNITY_FOG_LERP_COLOR(col,fogCol,coord)  
  11.   
  12.     //【1-2】 Shader Model 3.0和PC/游戏主机平台:计算雾效因子以及进行雾颜色的插值 ||SM3.0 and PC/console: calculate fog factor and lerp fog color  
  13.     #else  
  14.         //定义 UNITY_APPLY_FOG_COLOR(coord,col,fogCol)等价于UNITY_CALC_FOG_FACTOR(coord); UNITY_FOG_LERP_COLOR(col,fogCol,unityFogFactor)  
  15.         #define UNITY_APPLY_FOG_COLOR(coord,col,fogCol) UNITY_CALC_FOG_FACTOR(coord); UNITY_FOG_LERP_COLOR(col,fogCol,unityFogFactor)  
  16.     #endif  
  17. //【2】否则,直接定义UNITY_APPLY_FOG_COLOR宏  
  18. #else  
  19.     #define UNITY_APPLY_FOG_COLOR(coord,col,fogCol)  
  20. #endif  
  21. //【3】若定义了UNITY_PASS_FORWARDADD(正向附加渲染通道)宏  
  22. #ifdef UNITY_PASS_FORWARDADD  
  23.     //定义UNITY_APPLY_FOG(coord,col) 等价于UNITY_APPLY_FOG_COLOR(coord,col,fixed4(0,0,0,0))  
  24.     #define UNITY_APPLY_FOG(coord,col) UNITY_APPLY_FOG_COLOR(coord,col,fixed4(0,0,0,0))  
  25. //【4】否则,UNITY_APPLY_FOG(coord,col) 等价于 UNITY_APPLY_FOG_COLOR(coord,col,unity_FogColor)  
  26. #else  
  27.     #define UNITY_APPLY_FOG(coord,col) UNITY_APPLY_FOG_COLOR(coord,col,unity_FogColor)  
  28. #endif  



 
11.OutputForward函数

OutputForward函数定义于UnityStandardCore.cginc头文件中,其为正向渲染通道的输出函数。
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //-----------------------------【函数OutputForward】----------------------------------------------  
  2. // 用途:正向渲染通道输出函数  
  3. //  输入参数:一个half4类型的一个颜色值output,一个half型的透明度值alphaFromSurface  
  4. // 返回值:经过透明处理的half4型的输出颜色值  
  5. //-------------------------------------------------------------------------------------------------  
  6. half4 OutputForward (half4 output, half alphaFromSurface)  
  7. {  
  8.     #if defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON)  
  9.         output.a = alphaFromSurface;  
  10.     #else  
  11.         UNITY_OPAQUE_ALPHA(output.a);  
  12.     #endif  
  13.     return output;  
  14. }  

其中UNITY_OPAQUE_ALPHA宏的定义为:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. #define UNITY_OPAQUE_ALPHA(outputAlpha) outputAlpha = 1.0  



 
 
三、屏幕像素化特效的实现
 
 

我们都知道,Unity中的屏幕特效通常分为两部分来实现:

  • Shader实现部分
  • 脚本实现部分
下面依旧是从这两个方面对本次的特效进行实现。
 
 
3.1 Shader实现部分
 
 
国际惯例,上注释好的Shader代码。
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. Shader "浅墨Shader编程/Volume11/PixelEffect"  
  2. {  
  3.     //------------------------------------【属性值】------------------------------------  
  4.     Properties  
  5.     {  
  6.     //主纹理  
  7.     _MainTex("Texture", 2D) = "white" {}  
  8.     //封装的变量值  
  9.     _Params("PixelNumPerRow (X) Ratio (Y)", Vector) = (80, 1, 1, 1.5)  
  10. }  
  11.   
  12.     //------------------------------------【唯一的子着色器】------------------------------------  
  13.     SubShader  
  14.     {  
  15.         //关闭剔除操作  
  16.         Cull Off  
  17.         //关闭深度写入模式  
  18.         ZWrite Off  
  19.         //设置深度测试模式:渲染所有像素.等同于关闭透明度测试(AlphaTest Off)  
  20.         ZTest Always  
  21.   
  22.         //--------------------------------唯一的通道-------------------------------  
  23.         Pass  
  24.         {  
  25.             //===========开启CG着色器语言编写模块===========  
  26.             CGPROGRAM  
  27.   
  28.             //编译指令:告知编译器顶点和片段着色函数的名称  
  29.             #pragma vertex vert  
  30.             #pragma fragment frag  
  31.   
  32.             //包含头文件  
  33.             #include "UnityCG.cginc"  
  34.   
  35.             //顶点着色器输入结构  
  36.             struct vertexInput  
  37.             {  
  38.                 float4 vertex : POSITION;//顶点位置  
  39.                 float2 uv : TEXCOORD0;//一级纹理坐标  
  40.             };  
  41.   
  42.             //顶点着色器输出结构  
  43.             struct vertexOutput  
  44.             {  
  45.                 float4 vertex : SV_POSITION;//像素位置  
  46.                 float2 uv : TEXCOORD0;//一级纹理坐标  
  47.             };  
  48.   
  49.             //--------------------------------【顶点着色函数】-----------------------------  
  50.             // 输入:顶点输入结构体  
  51.             // 输出:顶点输出结构体  
  52.             //---------------------------------------------------------------------------------  
  53.             //顶点着色函数  
  54.             vertexOutput vert(vertexInput   v)  
  55.             {  
  56.                 //【1】实例化一个输入结构体  
  57.                 vertexOutput o;  
  58.                 //【2】填充此输出结构  
  59.                 //输出的顶点位置(像素位置)为模型视图投影矩阵乘以顶点位置,也就是将三维空间中的坐标投影到了二维窗口  
  60.                 o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);  
  61.                 //输入的UV纹理坐标为顶点输出的坐标  
  62.                 o.uv = v.uv;  
  63.   
  64.                 //【3】返回此输出结构对象  
  65.                 return o;  
  66.             }  
  67.   
  68.             //变量的声明  
  69.             sampler2D _MainTex;  
  70.             half4 _Params;  
  71.   
  72.             //进行像素化操作的自定义函数PixelateOperation  
  73.             half4 PixelateOperation(sampler2D tex, half2 uv, half scale, half ratio)  
  74.             {  
  75.                 //【1】计算每个像素块的尺寸  
  76.                 half PixelSize = 1.0 / scale;  
  77.                 //【2】取整计算每个像素块的坐标值,ceil函数,对输入参数向上取整  
  78.                 half coordX=PixelSize * ceil(uv.x / PixelSize);  
  79.                 half coordY = (ratio * PixelSize)* ceil(uv.y / PixelSize / ratio);  
  80.                 //【3】组合坐标值  
  81.                 half2 coord = half2(coordX,coordY);  
  82.                 //【4】返回坐标值  
  83.                 return half4(tex2D(tex, coord).xyzw);  
  84.             }  
  85.   
  86.             //--------------------------------【片段着色函数】-----------------------------  
  87.             // 输入:顶点输出结构体  
  88.             // 输出:float4型的像素颜色值  
  89.             //---------------------------------------------------------------------------------  
  90.             fixed4 frag(vertexOutput  Input) : COLOR  
  91.             {  
  92.                 //使用自定义的PixelateOperation函数,计算每个像素经过取整后的颜色值  
  93.                 return PixelateOperation(_MainTex, Input.uv, _Params.x, _Params.y);  
  94.             }  
  95.   
  96.             //===========结束CG着色器语言编写模块===========  
  97.             ENDCG  
  98.         }  
  99.     }  
  100. }  

如Shader代码中所展示的,本次的屏幕像素化特效主要用一个自定义函数来实现,实现代码如下:
[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //进行像素化操作的自定义函数PixelateOperation  
  2.             half4 PixelateOperation(sampler2D tex, half2 uv, half scale, half ratio)  
  3.             {  
  4.                 //【1】计算每个像素块的尺寸  
  5.                 half PixelSize = 1.0 / scale;  
  6.                 //【2】取整计算每个像素块的坐标值,ceil函数,对输入参数向上取整  
  7.                 half coordX=PixelSize * ceil(uv.x / PixelSize);  
  8.                 half coordY=( ratio * PixelSize ) * ceil(uv.y / PixelSize / ratio);  
  9.                 //【3】组合坐标值  
  10.                 half2 coord = half2(coordX,coordY);  
  11.                 //【4】返回坐标值  
  12.                 return half4(tex2D(tex, coord).xyzw);  
  13.             }  

首先需要了解到的是,此自定义函数中用到了CG标准函数库中的一个库函数——ceil。ceil(x)的作用是对输入参数向上取整。例如:ceil(float(1.3)) ,返回值就为2.0。
 
PixelateOperation函数的首先先计算出每个像素块的尺寸,然后根据这里的向上取整函数ceil,分别表示出像素块的坐标值。X坐标值为PixelSize * ceil(uv.x / PixelSize)。而Y轴这边还引入了一个系数ratio,先在式子一开头乘以此系数,然后在ceil函数之中的分母部分除以一个ratio,以达到用此参数实现自定义像素长宽比的调整操作。
 

然后在片段着色器中调用此自定义的PixelateOperation函数,其返回值就作为片段函数frag的返回值即可:

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. fixed4 frag(vertexOutput  Input) : COLOR  
  2.     {  
  3.         //使用自定义的PixelateOperation函数,计算每个像素经过取整后的颜色值  
  4.         return PixelateOperation(_MainTex, Input.uv, _Params.x, _Params.y);  
  5.     }  



       

        

 
3.2 C#脚本实现部分
 


C#脚本文件的代码依然是几乎从之前的几个特效中重用,只用稍微改一点细节就可以。贴出详细注释的实现此特效的C#脚本:

[csharp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. //设置在编辑模式下也执行该脚本  
  5. [ExecuteInEditMode]  
  6. //添加选项到菜单中  
  7. [AddComponentMenu("浅墨Shader编程/Volume11/PixelEffect")]  
  8. public class PixelEffect : MonoBehaviour   
  9. {  
  10.     //-----------------------------变量声明部分---------------------------  
  11.     #region Variables  
  12.   
  13.     //着色器和材质实例  
  14.     public Shader CurShader;  
  15.     private Material CurMaterial;  
  16.   
  17.     //三个可调节的自定义参数  
  18.     [Range(1f, 1024f), Tooltip("屏幕每行将被均分为多少个像素块")]  
  19.     public float PixelNumPerRow = 580.0f;  
  20.   
  21.     [Tooltip("自动计算平方像素所需的长宽比与否")]  
  22.     public bool AutoCalulateRatio = true;  
  23.   
  24.     [Range(0f, 24f), Tooltip("此参数用于自定义长宽比")]  
  25.     public float Ratio = 1.0f;  
  26.  
  27.     #endregion  
  28.   
  29.   
  30.     //-------------------------材质的get&set----------------------------  
  31.     #region MaterialGetAndSet  
  32.     Material material  
  33.     {  
  34.         get  
  35.         {  
  36.             if(CurMaterial == null)  
  37.             {  
  38.                 CurMaterial = new Material(CurShader);  
  39.                 CurMaterial.hideFlags = HideFlags.HideAndDontSave;    
  40.             }  
  41.             return CurMaterial;  
  42.         }  
  43.     }  
  44.     #endregion  
  45.   
  46.     //-----------------------------------------【Start()函数】---------------------------------------------    
  47.     // 说明:此函数仅在Update函数第一次被调用前被调用  
  48.     //--------------------------------------------------------------------------------------------------------  
  49.     void Start ()   
  50.     {  
  51.         //找到当前的Shader文件  
  52.         CurShader = Shader.Find("浅墨Shader编程/Volume11/PixelEffect");  
  53.   
  54.         //判断当前设备是否支持屏幕特效  
  55.         if(!SystemInfo.supportsImageEffects)  
  56.         {  
  57.             enabled = false;  
  58.             return;  
  59.         }  
  60.     }  
  61.   
  62.     //-------------------------------------【OnRenderImage()函数】------------------------------------    
  63.     // 说明:此函数在当完成所有渲染图片后被调用,用来渲染图片后期效果  
  64.     //--------------------------------------------------------------------------------------------------------  
  65.     void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)  
  66.     {  
  67.         //着色器实例不为空,就进行参数设置  
  68.         if(CurShader != null)  
  69.         {  
  70.             float pixelNumPerRow = PixelNumPerRow;  
  71.             //给Shader中的外部变量赋值  
  72.             material.SetVector("_Params"new Vector2(pixelNumPerRow,   
  73.                 AutoCalulateRatio ? ((float)sourceTexture.width / (float)sourceTexture.height) : Ratio ));  
  74.   
  75.             Graphics.Blit(sourceTexture, destTexture, material);  
  76.         }  
  77.   
  78.         //着色器实例为空,直接拷贝屏幕上的效果。此情况下是没有实现屏幕特效的  
  79.         else  
  80.         {  
  81.             //直接拷贝源纹理到目标渲染纹理  
  82.             Graphics.Blit(sourceTexture, destTexture);  
  83.         }  
  84.     }  
  85.   
  86.     //-----------------------------------------【Update()函数】----------------------------------------  
  87.     // 说明:此函数在每一帧中都会被调用    
  88.     //------------------------------------------------------------------------------------------------------  
  89.     void Update()  
  90.     {  
  91.         //若程序在运行,进行赋值  
  92.         if (Application.isPlaying)  
  93.         {  
  94.          #if UNITY_EDITOR  
  95.             if (Application.isPlaying != true)  
  96.             {  
  97.                 CurShader = Shader.Find("浅墨Shader编程/Volume11/PixelEffect");  
  98.             }  
  99.         #endif  
  100.         }  
  101.     }  
  102.     //-----------------------------------------【OnDisable()函数】---------------------------------------    
  103.     // 说明:当对象变为不可用或非激活状态时此函数便被调用    
  104.     //--------------------------------------------------------------------------------------------------------  
  105.     void OnDisable ()  
  106.     {  
  107.         if(CurMaterial)  
  108.         {  
  109.             //立即销毁材质实例  
  110.             DestroyImmediate(CurMaterial);    
  111.         }         
  112.     }  
  113. }  
根据我们C#脚本中参数的设定,可以有每行每列的像素个数PixelNumPerRow参数、是否自动计算正方形像素所需的长宽比与否AutoCalulateRatio参数、自定义长宽比的Ratio参数可以调节。而需要注意,若AutoCalulateRatio参数被勾选,我们的Shader将自动计算正方形像素所需的长宽比,这样第三个参数Ratio也就失效了。反正,若AutoCalulateRatio参数没有被勾选,就可以用Ratio参数自己定制像素的长宽比。

 
下面依然是一起看一下运行效果的对比。
 
 


四、最终的效果展示
 

还是那句话,贴几张场景的效果图和使用了屏幕特效后的效果图。在试玩场景时,除了类似CS/CF的FPS游戏控制系统以外,还可以使用键盘上的按键【F】,开启或者屏幕特效。
 
 
推车与货物(with 屏幕像素化特效):
 

推车与货物(原始场景):
 

城镇中(with 屏幕像素化特效):


 
城镇中(原始 场景 ):

 
 
悠长小径(with 屏幕像素化特效):


 
悠长小径(原始 场景 ):

 
 
山丘(with 屏幕像素化特效):

 

山丘(原始场景):

 
天色渐暗(with 屏幕像素化特效):

 
 
天色渐暗(原始 场景 ):

 
 
云端(with 屏幕像素化特效):

 
云端 原始 场景 ):
 
 图就贴这些,更多画面大家可以从文章开头下载的本文配套的exe场景,进行试玩,或者在本文附录中贴出的下载链接中下载本文配套的所有游戏资源的工程。 考虑到有读者朋友反映有时候打包出的unitypackage包会因为unity自身的bug不好打开。干脆从本期开始,我们以后项目工程就直接传项目的压缩包。大家解压出文件夹,然后直接用Unity打开即可。

至此,本文结束。感谢大家的捧场,我们下次更新再会。

PS:最近一段时间临近硕士毕业,有不少学业方面的事情需要处理,博客得停更一段时间,请见谅。





附: 本博文相关下载链接清单

【百度云】博文示例场景exe下载
【百度云】博文示例场景资源和源码工程下载
【Github】屏幕像素化特效实现源码


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值