Shader学习笔记(三)自定义光照模型,经典光照模型Lambert与HalfLambert

来源:互联网 发布:单片机一键开关机 编辑:程序博客网 时间:2024/06/09 13:55

自定义光照模型


#pragma surface surfaceFaction lightModel

surfaceFaction:着色器代码的方法的名字

lightModel:光照模型的名称


自定义光照模型的命名规则是Lighting+光照模型的名称

光照模型有5种原型:

half4 LightingName(SurfaceOutput s,fixed3 lightDir,half atten);

half4 LightingName(SurfaceOutput s,fixed3 lightDir,fixed3 viewDir,half atten);

half4 LightingName_PrePass(SurfaceOutput s,half4 light);

half4 LightingName_DirLightmap(SurfaceOutput s,fixed4 color,fixed4 scale,bool surfFuncWritesNormal);

half4 LightingName_DirLightmap(SurfaceOutput s,fixed4 color,fixed4 scale,fixed3 viewDir,bool surFuncWritesNormal,out half3 specColor);


例子:Lambert光照模型

#pragma surface surf BasicDiffuse

inline float4 LightingBasicDiffuse(SurfaceOutput s,fixed3 lightDir,fixed atten){float difLight=max(0,dot(s.Normal,lightDir));float4 col;col.rgb=s.Albedo*_LightColor0.rgb*(difLight*atten*2);//col.a=s.Alpha;return col;}

LightBasicDiffuse函数输出的是一个surface上某一点的颜色值和透明度值。s是上一个surf函数的输出,LightDir是光线方向,光源到物体表面上的点的向量,是单位向量。atten是衰减度,光线被物体反射之后会有能量损失,是Unity内置的一个参数。


float difLight=max(0,dot(s.Normal,lightDir));//计算漫反射的光强,值越大表示法线与光线间的夹角越小,这个点越亮

col.rgb=s.Albedo*_LightColor0.rgb*(difLight*atten*2);//_LightColor0.rgb表示光线的颜色,根据场景中的光源得到的,在Lighting.cginc中有声明,颜色值=反射值X平行光的颜色值X漫反射光强X衰减度X2


HalfLambert光照模型

#pragma surface surf HalfLambert


inline float4 LightingHalfLambert(SurfaceOutput s,fixed3 lightDir,fixed atten){float difLight=dot(s.Normal,lightDir);float halfLambert = 0.5 * difLight + 0.5;float4 col;col.rgb=s.Albedo*_LightColor0.rgb*(halfLambert*atten*2);col.a=s.Alpha;return col;}


Lambert光照模型的漫反射光强区间dot(s.Normal,lightDir)小于0 的部分直接为0,效果是背光的一面也是黑色的,HalfLambert光照模型,小于0的部分会从0渐变到0.5,颜色的灰度是有变化的。同时,亮部的亮度也提高了。 用于低光区域照亮物体,防止某个物体背光面丢失形状显得太过平面化。


 #Lambert#



#HalfLambert#








0 0
原创粉丝点击