第 11 课:Spot Light - Soft edges
实现
uniform float iTime;
uniform sampler2D iChannel0;
uniform sampler2D iChannel1;
varying vec3 vPos;
varying vec3 vNormal;
varying vec2 vUv;
vec3 getSpotLightDir() {
float dx = cos(iTime) * 0.25;
float dy = sin(iTime) * 0.25;
return normalize(vec3(0.0, 0.0, -1.0) + vec3(dx, dy, 0.0));
}
void main() {
vec3 viewPos = vec3(-4.0, 0.0, 2.5);
vec3 objectColor = texture2D(iChannel0, vUv).rgb;
vec3 objectSpecular = texture2D(iChannel1, vUv).rgb;
vec3 fragNormal = normalize(vNormal);
vec3 fragPos = vPos;
vec3 lightColor = vec3(1.0, 1.0, 0.75);
vec3 lightPos = vec3(0.0, 0.0, 2.0);
vec3 lightDir = normalize(lightPos - fragPos);
float ambient = 0.2;
float diffuse = max(dot(fragNormal, lightDir), 0.0);
vec3 viewDir = normalize(viewPos - fragPos);
vec3 reflectDir = reflect(-lightDir, fragNormal);
float specular = max(dot(viewDir, reflectDir), 0.0);
specular = pow(specular, 32.0);
vec3 spotLightDir = getSpotLightDir();
float spotLightCosDiff = dot(spotLightDir, -lightDir);
float cosCutOffAngleInner = cos(radians(10.0));
float cosCutOffAngleOuter = cos(radians(12.0));
float intensity = smoothstep(cosCutOffAngleOuter, cosCutOffAngleInner, spotLightCosDiff);
diffuse = diffuse * intensity;
specular = specular * intensity;
vec3 result = vec3(0.0);
result += ambient * objectColor;
result += diffuse * objectColor;
result += specular * objectSpecular;
result *= lightColor;
gl_FragColor = vec4(result, 1.0);
}