先上图:
这光照是在顶点着色器里计算的,如果在片元着色器中计算效果会好一些。
然后是代码:
Shader "Custom/ShaderExample8"
{
Properties
{
_Color ("Diffuse Material Color", Color) = (1, 1, 1, 1)
_SpecColor ("Specular Material Color", Color) = (1, 1, 1, 1)
_Shininess ("Shininess", Float) = 10 //smoothness
}
SubShader
{
Pass
{
Tags {"LightMode" = "ForwardBase"}
GLSLPROGRAM
uniform vec4 _Color;
uniform vec4 _SpecColor;
uniform float _Shininess;
uniform vec3 _WorldSpaceCameraPos;
uniform mat4 _Object2World;
uniform mat4 _World2Object;
uniform vec4 _WorldSpaceLightPos0;
uniform vec4 _LightColor0;
#ifdef VERTEX
//顶点着色器
out vec4 desColor; //在顶点着色器计算color
void main()
{
mat4 modelMatrix = _Object2World;
mat4 modelMatrixInverse = _World2Object;
//世界normal
vec3 normalDirection = normalize(vec3(vec4(gl_Normal, 0.0) * modelMatrixInverse));
//view dir
vec3 viewDirection = normalize(vec3(vec4(_WorldSpaceCameraPos, 1.0) - modelMatrix * gl_Vertex));
//light dir
vec3 lightDirection;
//衰减factor
float attenuation;
if (0.0 == _WorldSpaceLightPos0.w) //方向光源
{
attenuation = 1.0; //无衰减
lightDirection = normalize(vec3(_WorldSpaceLightPos0));
}
else //点光源或聚光灯
{
vec3 vertexToLightSource = vec3(_WorldSpaceLightPos0 - modelMatrix * gl_Vertex);
float lightDistance = length(vertexToLightSource);
attenuation = 1.0 / lightDistance; //线性衰减
lightDirection = normalize(vertexToLightSource);
}
vec3 ambientLighting = vec3(gl_LightModel.ambient) * vec3(_Color);
//计算diffuse
vec3 diffuseReflection = attenuation * vec3(_LightColor0) * vec3(_Color) * max(0.0, dot(normalDirection, lightDirection));
vec3 halfVector = normalize(lightDirection + normalDirection);
//计算specular,这是普通反射,后面会加入菲涅尔反射
vec3 specularReflection;
//角度大于90度,表示在背面
if (dot(normalDirection, lightDirection) < 0.0)
{
specularReflection = vec3(0.0, 0.0, 0.0);
}
else //正面
{
//这里有两种计算方式,一种没用halfVector,一种用halfVector
//specularReflection = attenuation * vec3(_LightColor0) * vec3(_SpecColor)
// * pow(max(0.0, dot(reflect(-lightDirection, normalDirection), viewDirection)), _Shininess);
specularReflection = attenuation * vec3(_LightColor0) * vec3(_SpecColor)
* pow(max(0.0, dot(halfVector, normalDirection)), _Shininess);
}
desColor = vec4(ambientLighting + diffuseReflection + specularReflection, 1.0);
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
#endif
#ifdef FRAGMENT
//片元着色器
in vec4 desColor;
void main()
{
gl_FragColor = desColor;
}
#endif
ENDGLSL
}
}
}