1

我有一个 Model2D 类,其中包含以下内容:

class Model2D
{
    public: //it's private, but I'm shortening it here
    unsigned char* bitmapImage;
    unsigned int textureID;
    int imageWidth, imageHeight;

    void Load(char* bitmapFilename);
}
void Model2D::Load(char* bitmapFilename)
{
    ifstream readerBMP;
    readerBMP.open(bitmapFilename, ios::binary);
    //I get the BMP header and fill the width, height

    bitmapImage = new GLubyte[imageWidth * imageHeight * 4];
    //Loop to read all the info in the BMP and fill the image array, close reader

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, bitmapImage);
}
void Model2D::Draw()
{
    glBegin(GL_QUADS);          
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    glBindTexture(GL_TEXTURE_2D, textureID);

    float texScale = 500.0; //this is just so I don't have to resize images

    glTexCoord2f(0.0, 0.0); glVertex3f(-(imageWidth / texScale), -(imageHeight / texScale), 0.0);
    glTexCoord2f(0.0, 1.0); glVertex3f(-(imageWidth / texScale), (imageHeight / texScale), 0.0);
    glTexCoord2f(1.0, 1.0); glVertex3f((imageWidth / texScale), (imageHeight / texScale), 0.0);
    glTexCoord2f(1.0, 0.0); glVertex3f((imageWidth / texScale), -(imageHeight / texScale), 0.0);    
}

在我的主循环中,我有:

Model2D spritest;
spritest.LoadFromScript("FirstBMP.bmp");
spritest.Z(-5); spritest.X(-2);

Model2D spritest2;
spritest2.LoadFromScript("SecondBMP.bmp");
spritest2.X(+2); spritest2.Z(-6);

//...
//main loop
spritest.Draw();
spritest2.Draw();

调试时似乎工作正常,位图的地址不同,OpenGL生成的纹理ID也不同,它们也被正确调用,调试时X,Y和Z位置也正确,但由于某些未知原因,spritest图像数据被sprites2覆盖。即使我不从sprites2调用 Draw() ,也会显示图像而不是spritest

这可能是什么原因造成的?

4

1 回答 1

1

glBegin必须在您的纹理绑定功能之后Draw

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, textureID);
glBegin(GL_QUADS);          

glBindTexture的文档中它指出:

当纹理绑定到目标时,该目标的先前绑定会自动中断。

您还会发现在glBegin的文档中指出:

glBegin在和之间只能使用 GL 命令的子集glEnd。命令是glVertex, glColor, glSecondaryColor, glIndex, glNormal, glFogCoord, glTexCoord, glMultiTexCoord, glVertexAttrib, glEvalCoord, glEvalPoint, glArrayElement, glMaterial, 和glEdgeFlag. 此外,使用glCallListglCallLists执行仅包含上述命令的显示列表也是可以接受的。glBegin如果在和之间执行任何其他 GL 命令glEnd,则设置错误标志并忽略该命令。

因此,在您的Draw功能中,您将需要放置glBindTexture(GL_TEXTURE_2D, textureID);and glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);before glBegin(GL_QUADS)。否则,glBindTexture什么都不做,因为它在 a 内glBegin,因此SecondBMP.bmp仍然绑定到目标GL_TEXTURE_2D

于 2012-12-28T18:35:02.923 回答