高光反射计算公式:
我们需要4个参数,光源的颜色和强度,材质的高光反射系数,视角方向和反射方向.
在高光反射中我们要取得反射光线和视线的夹角.
Cg提供了反射光线的函数reflect(i,n)
###逐定点光照
1.声明三个属性,_Specular控制高光反射材质,_Diffuse漫反射材质,_Gloss控制高光区域大小
Properties
{
_Diffuse("Diffuse",Color) = (1,1,1,1)
_Specular("Specular",Color) = (1,1,1,1)
_Gloss("Gloss",Range(8.0,256)) = 20
}
2.在SubShader语句块中定义Pass语句块,Tags指明光照模式
SubShader{
Pass{
Tags{ "LightMode" = "ForwardBase"}
3.定义着色器 包含内置文件 定义结构体 定义与属性相同类型的变量等
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
fixed4 _Specular;
float _Gloss;
struct a2v {
float4 vertex:POSITION;
float3 normal:NORMAL;
};
struct v2f {
float4 pos : SV_POSITION;
float3 color : COLOR;
};
4.顶点着色器:包含了ambient环境光,diffuse漫反射光,specular高光
v2f vert(a2v v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
float4 ambient = UNITY_LIGHTMODEL_AMBIENT;
float3 worldNormal = normalize(mul(v.normal, (float3x3)_World2Object));
float3 worldLightDir = normalize(_WorldSpaceLightPos0);
fixed3 diffuse = _LightColor0.rgb*_Diffuse.rgb*saturate(dot(worldNormal, worldLightDir));
fixed3 reflectDir = normalize(reflect(-worldLightDir, worldNormal));
fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - mul(_Object2World,v.vertex).xyz);
fixed3 specular = _LightColor0.rgb*_Specular.rgb*pow(saturate(dot(reflectDir, viewDir)), _Gloss);
o.color = ambient + diffuse + specular;
return o;
}
5.片元着色器:输出色彩
fixed4 frag(v2f i):SV_Target {
return fixed4(i.color, 1.0);
}
###逐像素光照
逐像素渲染光照更加平滑
将光照的处理交给fragment
实现完整的Phong光照模型
struct v2f {
float4 pos : SV_POSITION;
float3 worldNormal : TEXCOORD0;
float3 worldPos : TEXCOORD1;
};
v2f vert(a2v v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
o.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject);
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
return o;
}
fixed4 frag(v2f i):SV_Target {
float4 ambient = UNITY_LIGHTMODEL_AMBIENT;
float3 worldNormal = normalize(i.worldNormal);
float3 worldLightDir = normalize(_WorldSpaceLightPos0);
fixed3 diffuse = _LightColor0.rgb*_Diffuse.rgb*saturate(dot(worldNormal, worldLightDir));
fixed3 reflectDir = normalize(reflect(-worldLightDir, worldNormal));
fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);
fixed3 specular = _LightColor0.rgb*_Specular.rgb*pow(saturate(dot(reflectDir, viewDir)), _Gloss);
fixed3 color = ambient + diffuse + specular;
return fixed4(color, 1.0);
}
###Blinn-Phong光照模型
在Blinn模型中我们引入一个新的矢量h
得到一个新的公式
fixed3 halfDir = normalize(worldLightDir + viewDir);
fixed3 specular = _LightColor0.rgb*_Specular.rgb*pow(saturate(dot(worldNormal,halfDir)), _Gloss);
更改高光部分的代码
对比Phong模型,高光部分更加明显