我有一个漫反射照明着色器,当对象不旋转时它似乎可以工作。但是,当我应用旋转变换时,灯光似乎也随着对象旋转。这就像物体和光线保持静止,但相机是围绕物体移动的相机。
这是我的顶点着色器代码:
#version 110
uniform mat4 projectionMatrix;
uniform mat4 modelviewMatrix;
uniform vec3 lightSource;
attribute vec3 vertex;
attribute vec3 normal;
varying vec2 texcoord;
void main() {
gl_Position = projectionMatrix * modelviewMatrix * vec4( vertex, 1.0 );
vec3 N = gl_NormalMatrix * normalize( normal );
vec4 V = modelviewMatrix * vec4( vertex, 1.0 );
vec3 L = normalize( lightSource - V.xyz );
float NdotL = max( 0.0, dot( N, L ) );
gl_FrontColor = vec4( gl_Color.xyz * NdotL, 1.0 );
gl_TexCoord[0] = gl_MultiTexCoord0;
}
这是进行旋转的代码:
scene.LoadIdentity();
scene.Translate( 0.0f, -5.0f, -20.0f );
scene.Rotate( angle, 0.0f, 1.0f, 0.0f );
object->Draw();
我在 object->Draw() 函数中通过 glUniform3f 发送了眼睛空间光的位置。光照位置是静态的,定义为:
glm::vec4 lightPos( light.x, light.y, light.z, 1.0 );
glm::vec4 lightEyePos = modelviewMatrix * lightPos;
glUniform3f( uniforms.lightSource, lightEyePos.x, lightEyePos.y, lightEyePos.z );
这种方法有什么问题?
编辑: glm::lookAt 代码
Scene scene;
scene.LoadMatrix( projection );
scene.SetMatrixMode( Scene::Modelview );
scene.LoadIdentity();
scene.SetViewMatrix( glm::lookAt( glm::vec3( 0.0f, 0.0f, 0.0f ), glm::vec3( 0.0f, -5.0f, -20.0f ), glm::vec3( 0.0f, 1.0f, 0.0f ) ) );
SetViewMatrix 代码:
void Scene::SetViewMatrix( const glm::mat4 &matrix ) {
viewMatrix = matrix;
TransformMatrix( matrix );
}
然后我只是将我使用的modelviewMatrix更改为viewMatrix:
glm::vec4 lightPos( light.x, light.y, light.z, 1.0 );
glm::vec4 lightEyePos = viewMatrix * lightPos;
glUniform3f( uniforms.lightSource, lightEyePos.x, lightEyePos.y, lightEyePos.z );