参考了wiki:https://en.wikibooks.org/wiki/GLSL_Programming/Unity/Specular_Highlights_at_Silhouettes
先上图:不过看不太出什么区别
然后是代码:
Shader "Custom/ShaderExample17"
{
Properties
{
_Color ("Diffuse Material Color", Color) = (1,1,1,1)
_SpecColor ("Specular Material Color", Color) = (1,1,1,1)
_Shininess ("Shininess", Float) = 10
_PowerFactor ("Power", Float) = 5
}
SubShader
{
Pass
{
Tags { "LightMode" = "ForwardBase" }
GLSLPROGRAM
uniform vec4 _Color;
uniform vec4 _SpecColor;
uniform float _Shininess;
uniform float _PowerFactor;
uniform vec3 _WorldSpaceCameraPos;
uniform mat4 _Object2World;
uniform mat4 _World2Object;
uniform vec4 _WorldSpaceLightPos0;
uniform vec4 _LightColor0;
#ifdef VERTEX
//顶点着色器
out vec4 position;
out vec3 worldNormalDirection;
void main()
{
mat4 modelMatrix = _Object2World;
mat4 modelMatrixInverse = _World2Object;
position = modelMatrix * gl_Vertex;
worldNormalDirection = normalize(vec3(vec4(gl_Normal, 0.0) * modelMatrixInverse));
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
#endif
#ifdef FRAGMENT
//片元着色器
in vec4 position;
in vec3 worldNormalDirection;
void main()
{
vec3 normalDirection = normalize(worldNormalDirection);
vec3 viewDirection = normalize(_WorldSpaceCameraPos - vec3(position));
vec3 lightDirection;
float attenuation;
if (0.0 == _WorldSpaceLightPos0.w) //方向光
{
attenuation = 1.0;
lightDirection = normalize(vec3(_WorldSpaceLightPos0));
}
else //点光源或聚光灯
{
vec3 vertexToLightSource = vec3(_WorldSpaceLightPos0 - position);
float ddistance = length(vertexToLightSource);
attenuation = 1.0 / ddistance;
lightDirection = normalize(vertexToLightSource);
}
//ambient
vec3 ambientLighting = vec3(gl_LightModel.ambient) * vec3(_Color);
//diffuse
vec3 diffuseReflection = attenuation * vec3(_LightColor0) * vec3(_Color)
* max(0.0, dot(normalDirection, lightDirection));
vec3 specularReflection;
if (dot(normalDirection, lightDirection) < 0.0)
{
specularReflection = vec3(0.0, 0.0, 0.0);
}
else
{
vec3 halfwayDirection = normalize(lightDirection + viewDirection);
float w = pow(1.0 - max(0.0, dot(halfwayDirection, viewDirection)), _PowerFactor);
specularReflection = attenuation * vec3(_LightColor0)
* mix(vec3(_SpecColor), vec3(1.0), w)
* pow(max(0.0, dot(reflect(-lightDirection, normalDirection), viewDirection)), _Shininess);
}
gl_FragColor = vec4(ambientLighting + diffuseReflection + specularReflection, 1.0);
}
#endif
ENDGLSL
}
}
}