我正在开发一个个人图形引擎,并开始开发聚光灯。问题是渲染不太合理。为了简单起见,我在以下着色器示例中清除了有关光线和纹理管理的所有信息。
以下是顶点着色器代码:
#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>
结果如下(更接近现实但仍不正确):
![enter image description here](https://istack.dev59.com/0RnDd.webp)
LightInfos[idx].Position.xyz
代替vec3(LightInfos[idx].Position)
,这通常更易读 :) - Jaa-c