VBO纹理不起作用

时间:2012-04-29 22:46:13

标签: opengl textures vbo

问题是这段代码什么都没显示。我的纹理负载有问题。如果我评论关于纹理处理的代码行,它可以很好地工作。它显示一个4色的正方形。你能救我吗?

#define OFFSET_BUFFER(bytes) ((GLfloat *)NULL + bytes)

GLfloat vertices[12] =
{
    -1.0f, -1.0f, 1.0f,
    -1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f,
    1.0f, -1.0f, 1.0f,
};

GLfloat colors[12] =
{
    1.0f, 0.0f, 0.0f,
    0.0f, 1.0f, 0.0f,
    0.0f, 0.0f, 1.0f,
    1.0f, 0.0f, 1.0f,
};

GLfloat texture[8] =
{
    0.0f, 0.0f,
    1.0f, 0.0f,
    1.0f, 1.0f,
    0.0f, 1.0f
};

int main(int argc, char *argv[])
{
    SDL_Init(SDL_INIT_VIDEO);
    SDL_WM_SetCaption("Texture Mapping",NULL);
    SDL_SetVideoMode(500, 500, 32, SDL_OPENGL);

    bool continuer = true;
    SDL_Event event;
    GLuint  buf[2];
    GLuint texture1;

    glClearDepth(1.0f);
    glClearColor(0.1f, 0.1f, 0.1f, 0.1f);
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(70.0f, (float)500.0f / (float)500.0f, 1.0f, 3000.0f);
    glewInit();

    texture1 = loadTexture("caisse.jpg");
    glBindTexture(GL_TEXTURE_2D, texture1);

    glGenBuffers(2, &buf[0]);
    glBindBuffer(GL_ARRAY_BUFFER, buf[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, buf[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, texture1);
    glBufferData(GL_ARRAY_BUFFER, sizeof(texture), texture, GL_STATIC_DRAW);

    while (continuer)
    {
        SDL_WaitEvent(&event);
        switch(event.type)
        {
            case SDL_QUIT:
                continuer = false;
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glEnable(GL_TEXTURE_2D);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        gluLookAt(0.0f, 0.0f, 3.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

        glBindBuffer(GL_ARRAY_BUFFER, buf[0]);
        glVertexPointer(3, GL_FLOAT, 0, OFFSET_BUFFER(0));

        glBindBuffer(GL_ARRAY_BUFFER, buf[1]);
        glColorPointer(3, GL_FLOAT, 0, OFFSET_BUFFER(0));

        glBindBuffer(GL_ARRAY_BUFFER, texture1);
        glTexCoordPointer(2, GL_FLOAT, 0, OFFSET_BUFFER(0));

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_COLOR_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glDrawArrays(GL_QUADS, 0, 4);

        glDisableClientState(GL_TEXTURE_COORD_ARRAY);   
        glDisableClientState(GL_COLOR_ARRAY);
        glDisableClientState(GL_VERTEX_ARRAY);


        glDisable(GL_TEXTURE_2D);

        glFlush();
        SDL_GL_SwapBuffers();
    }

    SDL_Quit();

    return 0;
}

1 个答案:

答案 0 :(得分:2)

首先,您需要开始在代码中添加glGetError()以进行调试,因为您肯定会在此处生成一些错误。

您正在使用glBindBuffer绑定纹理texture1,这样做是不正确的。纹理坐标与纹理不同。您应该生成3个缓冲区而不是2个缓冲区,并将texture[8] texcoords加载到第三个缓冲区中。