简单的GLSL示例未在屏幕上显示任何内容

时间:2013-01-19 19:52:27

标签: c++ opengl glsl shader

我正在尝试使用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;
}

1 个答案:

答案 0 :(得分:0)

根据顶点,颜色等的定义方式,sizeof(顶点)可能只返回指针的大小。尝试:

3*numVertices*sizeof(float)