【发布时间】:2013-01-19 19:52:26
【问题描述】:
我正在尝试使用 GLSL 打印一个简单的立方体,但我只得到一个空屏幕。我不知道我做错了什么。顶点、法线、三角形从 Blender 中导出。
void InitBuffers() {
// monkey vertices, normals
readVerticesNormals();
// cube vertices
glGenVertexArraysAPPLE(1, &CubeVao);
glBindVertexArrayAPPLE(CubeVao);
glGenBuffers(1, &CubeVboPositions);
glBindBuffer(GL_ARRAY_BUFFER,CubeVboPositions);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glGenBuffers(1,&CubeVboColors);
glBindBuffer(GL_ARRAY_BUFFER, CubeVboColors);
glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glGenBuffers(1, &CubeNormals);
glBindBuffer(GL_ARRAY_BUFFER, CubeNormals);
glBufferData(GL_ARRAY_BUFFER, sizeof(normals), normals, GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);
glGenBuffers(1, &CubeIbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, CubeIbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(triangles), triangles, GL_STATIC_DRAW);
}
我将顶点数据绑定到着色器。
glBindAttribLocation(ProgramShader, 0, "position");
glBindAttribLocation(ProgramShader, 1, "color");
glBindAttribLocation(ProgramShader, 2, "normal");
相机位于 (0,0,0) 并朝向 (0,0,-1)。对象,在本例中为立方体,它位于 (0,0,-4)。 渲染函数是:
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,0,0);
// set view matrix
ViewMatrix.setView(0,0,0,0,0,-1,0,1,0);
// use shader program
glUseProgram(ProgramShader);
// send uniforms to shader
glUniformMatrix4fv(ProjectionMatrixLocation, 1, false, ProjectionMatrix.m);
glUniformMatrix4fv(ViewMatrixLocation, 1, false, ViewMatrix.m);
glUniformMatrix4fv(ModelMatrixLocation, 1, false, ModelMatrix.m);
glBindVertexArrayAPPLE(CubeVao);
glDrawElements(GL_TRIANGLES, 3*tri_num, GL_UNSIGNED_INT, (void*)0);
glutSwapBuffers();
}
顶点着色器:
attribute vec3 position;
attribute vec3 color;
attribute vec3 normal;
uniform mat4 modelMatrix,viewMatrix,projMatrix;
varying vec4 Normal;
varying vec4 Position;
varying vec4 Color;
void main() {
// position in view space
Position = viewMatrix * modelMatrix * vec4(position, 1.0);
// normal in view space
Normal = normalize(viewMatrix * modelMatrix * vec4(normal, 1.0));
Color = vec4(color, 1.0);
// final position
gl_Position = projMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
}
片段着色器:
varying vec4 Normal;
varying vec4 Position;
varying vec4 Color;
void main() {
gl_FragColor = Color;
}
【问题讨论】:
-
你试过
gl_FragColor = vec4(1.0);吗?这将只向您显示几何图形(一切都被绘制成白色)。如果它仍然是黑色的,那么你的几何/顶点着色器是错误的;如果不是,你的颜色是错误的。另外,请确保您的着色器程序已正确编译和链接(转储 GLSL 编译器消息总是一个好主意) -
编译日志说什么?是否有任何 OpenGL 错误? How far can you narrow down your code? 只是在这里倾倒数百行代码,不像在这里请任何人帮忙。
-
我没有错误也没有警告。此外,颜色被硬编码为 (0.50, 0.45, 0.87)。
-
仅供参考,您不能以与位置相同的方式转换法线,但这不是什么都不显示的原因。