#version 430 core
uniform vec4 Ambient; //环境光
uniform vec3 LightColor; //聚光灯颜色
uniform vec3 LightPosition; //聚光灯位置
uniform vec3 SoptDirection; //聚光灯中心灯光方向
uniform float SoptCosCutoff; //聚光灯范围
uniform float SoptExponent; //聚光灯指数
uniform float Shininess;
uniform float Strength; //强度
uniform vec3 EyeDirection; //视线方向
uniform float Attionuation; //衰减系数
in vec4 color;
in vec3 Normal;
in vec4 Pos;
out vec4 FragColor;
void main()
{
//从聚光灯指向片元的向量
vec3 lightDir = vec3(Pos.xyz) - LightPosition;
//聚光灯和片元距离
float len = length(lightDir);
//规一化
lightDir = normalize(lightDir);
//减,相当于加上反方向,半角向量
vec3 HalfVector = normalize(EyeDirection - lightDir);
//根据距离求出衰减值
float Attenua = 1 / (Attionuation*(1.0+len*len));
//漫反射 相当于max(0.0f, dot(Normal, -lightDir)) *0.6
float diffuse = max(0.0f, -1*dot(Normal, lightDir)) *0.6;
//镜面高光
float specular = max(0.0f,dot(Normal, HalfVector));
//基本平行时没有高光
if(diffuse <= 0.00001)
specular = 0.0f;
else
specular = pow(specular, Shininess);
//cos夹角值
float Spotcos = dot(SoptDirection, lightDir);
//夹角越大,cos值越小,大于聚光灯范围时没有聚光灯效果
if(Spotcos < SoptCosCutoff)
{
Attenua = 0.0f;
}
else
{
//specular *= pow(Spotcos, SoptExponent);
specular *= ((Spotcos-1)/(1-SoptCosCutoff) + 1 )*2.0*Strength;
}
//环境光加漫反射
vec4 scatteredLight = Ambient + vec4(LightColor * diffuse*Attenua, 0.0);
//高光
vec4 ReflectLight = vec4(LightColor*specular*Attenua, 0.0);
//最终颜色
FragColor = min(color*scatteredLight + ReflectLight, vec4(1.0));
}
OpenGL聚光灯实现注解
最新推荐文章于 2024-02-06 16:36:38 发布