2012-09-21 42 views
0

我正在从OpenGL 4.0着色语言菜谱实现漫反射每个顶点着色器,但稍微修改以适合我的项目。实现漫反射每个顶点着色器,不工作

这是我的顶点着色器代码:

layout(location = 0) in vec4 vertexCoord; 
layout(location = 1) in vec3 vertexNormal; 

uniform vec4 position; // Light position, initalized to vec4(100, 100, 100, 1) 
uniform vec3 diffuseReflectivity; // Initialized to vec3(0.8, 0.2, 0.7) 
uniform vec3 sourceIntensity; // Initialized to vec3(0.9, 1, 0.3) 

uniform mat4 projection; 
uniform mat4 view; 
uniform mat4 model; 

out vec3 LightIntensity; 

void main(void) { 
    // model should be the normalMatrix here in case that 
    // non-uniform scaling has been applied. 
    vec3 tnorm = normalize(vec3(model * vec4(vertexNormal, 0.0))); 

    // Convert to eye/camera space 
    vec4 eyeCoordsLightPos = view * model * position; 
    vec4 eyeCoords = view * model * vertexCoord; 
    vec3 s = normalize(vec3(eyeCoordsLightPos - eyeCoords)); 

    // Diffuse shading equation 
    LightIntensity = sourceIntensity * diffuseReflectivity * max(dot(s,tnorm), 0.0); 

    gl_Position = projection * view * model * vertexCoord; 
} 

这是我的片段着色器:

in vec3 LightIntensity; 

layout(location = 0) out vec4 FragColor; 

void main(){ 
    FragColor = vec4(LightIntensity, 1.0); 
} 

我渲染一个框,我对所有的法线值。然而盒子只是黑色。 假设我的制服在渲染时设置正确,我的着色器代码中是否有明显的错误?

与本书中的代码相比,我使用的模型矩阵作为普通矩阵,并将模型空间中的光位置传递,但将其转换为着色器中的相机空间。在片段着色器与FragColor = vec4(f_vertexNormal, 1.0);渲染时 Image of rendering, do not be confused by the shaded background which is a texture.

图片: enter image description here

更新代码与眼空间TNORM

渲染的图像,不通过阴影的背景这是一个纹理混淆建议:

void main(void) { 
    // model should be the normalMatrix here in case that 
    // non-uniform scaling has been applied. 
    vec3 tnorm = normalize(vec3(model * vec4(vertexNormal, 0.0))); 

    // Convert to eye/camera space 
    vec3 eyeTnorm = vec3(view * vec4(tnorm, 0.0)); 
    vec4 eyeCoordsLightPos = view * position; 
    vec4 eyeCoords = view * model * vertexCoord; 
    vec3 s = normalize(vec3(eyeCoordsLightPos - eyeCoords)); 

    // Diffuse shading equation 
    LightIntensity = sourceIntensity * diffuseReflectivity * max(dot(s,eyeTnorm), 0.0); 

    gl_Position = projection * view * model * vertexCoord; 
    f_vertexNormal = vertexNormal; 
} 
+0

您是否尝试输出一些中间信号?如果你用's'给盒子着色是黑色的?如果你用'vertexNormal'给盒子着色,它是黑色的吗?另外,对于我来说,你会用模型矩阵来改变灯光位置似乎有点不可思议,尽管我不认为这会导致它不能正常工作。 – Tim

+0

添加了一张图片,我使用vertexnormal作为颜色。看起来对我来说是正确的。我同意模型矩阵,它不一定。 – toeplitz

回答

2

除了上面我的评论,你是dot -ing aw orld空间矢量tnorm与眼睛空间矢量s。你只应该在同一个空间中点矢量。所以你可能要考虑将tnorm也转换为眼睛空间。

+0

我想你的意思是tnorm不是tvec? 这是它如何在书中: 'vec3 tnorm = normalize(NormalMatrix * VertexNormal)' – toeplitz

+0

添加了一个新的代码片段,我将tnorm转换为眼睛空间。仍是同样的黑色结果。 – toeplitz

+0

是的,你说得对,我的意思是'tnorm',对不起。在本书中,我假定NormalMatrix是一个将法线转换成眼睛空间的矩阵,类似于模型视图矩阵。在你的情况下,虽然normalMatrix正在转变为世界空间。 – Tim