我正在开发个人图形引擎,并开始开发聚光灯。问题是渲染不合逻辑。为简单起见,我在下面的着色器示例中清理了有关光和纹理管理的所有信息。
这是顶点着色器代码:
#version 400
layout (location = 0) in vec3 VertexPosition;
uniform mat4 ModelViewMatrix;
uniform mat4 MVP;
out vec3 VPosition;
void main(void)
{
VPosition = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0f)); //Eye coordinates vertex position
gl_Position = MVP * vec4(VertexPosition, 1.0f);
}
和片段着色器代码:
#version 400
in vec3 Position; //IN EYE COORDINATES
layout (location = 0) out vec4 FragColor;
uniform int lightCount;
struct SpotLight
{
vec4 Position; //ALREADY IN EYE COORDINATES
vec3 La, Ld, Ls;
vec3 direction;
float exponent;
float cutoff;
};
uniform SpotLight LightInfos[1];
vec3 getLightIntensity(void)
{
vec3 LightIntensity = vec3(0.0f);
for (int idx = 0; idx < lightCount; idx++)
{
vec3 lightDirNorm = normalize(vec3(LightInfos[idx].Position) - Position);
vec3 spotDirNorm = normalize(LightInfos[idx].direction);
float angle = acos(dot(-lightDirNorm, spotDirNorm));
float cutoff = radians(clamp(LightInfos[idx].cutoff, 0.0f, 90.0f));
vec3 ambient = vec3(0.1f, 0.1f, 0.8f); //Color out of the spotlight's cone.
vec3 spotColor = vec3(0.1f, 0.8f, 0.1f); //Color within the spotlight's cone.
if (angle < cutoff)
{
LightIntensity = spotColor;
}
else
{
LightIntensity = ambient;
}
}
return (LightIntensity);
}
void main(void)
{
FragColor = vec4(getLightIntensity(), 1.0f);
}
这是我发送灯光位置属性的 C++ 代码:
glm::vec4 lightPositionVec = viewMatrix * glm::vec4(lightPosition[0], lightPosition[1], lightPosition[2], lightPosition[3]);
program->setUniform(std::string("LightInfos[").append(Utils::toString<int>(idx)).append("].Position").c_str(), lightPositionVec);
这是聚光灯的属性:
<position x="0.0" y="2.0" z="0.0" w="1" />
<direction x="0.0" y="-1.0" z="0.0" />
<exponent>3.0</exponent>
<cutoff>50.0</cutoff>
视图属性:
<camera name="cam1">
<perspective fovy="70.0" ratio="1.0" nearClipPlane="0.1" farClipPlane="1000.0"/>
<lookat>
<eye x="0.0" y="50.0" z="50.0" />
<target x="0.0" y="0.0" z="0.0" />
<up x="0.0" y="1.0" z="0.0"/>
</lookat>
</camera>
我在将这些信息发送到我的 C++ 代码中的程序着色器之前检查了这些信息,它们是正确的。
结果如下:
如果我使用以下相机属性将相机放置在更靠近平面的位置:
<camera name="cam1">
<perspective fovy="70.0" ratio="1.0" nearClipPlane="0.1" farClipPlane="1000.0"/>
<lookat>
<eye x="0.0" y="10.0" z="20.0" />
<target x="0.0" y="0.0" z="0.0" />
<up x="0.0" y="1.0" z="0.0"/>
</lookat>
</camera>
结果如下(更接近现实但仍然不正确):
如您所见,这不合逻辑:我在 x=0、y=1、z=0、向下聚光灯方向(x=0、y=-1、z=0)有一个点,所以我没有理解这个结果。另外,我所有的向量都在眼睛坐标中。我的印象是聚光灯效果取决于相机的位置。有人可以帮助我吗?