[英]OpenGL Multiple Textures Loading Error
我有一个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生成的textureID也是如此,它们也被正确调用,并且调试时X,Y和Z位置也正确,但不知什么原因,spritest图像数据是由spritest2覆盖。 即使我不从spritest2调用Draw(),也将显示图像而不是spritest 。
是什么原因造成的?
glBegin
必须位于Draw
纹理绑定功能之后:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, textureID);
glBegin(GL_QUADS);
在glBindTexture的文档中,它指出:
将纹理绑定到目标后,该目标的先前绑定将自动断开。
您还会在glBegin文档中发现它指出:
glBegin
和glEnd
之间只能使用GL命令的子集。 命令是glVertex
,glColor
,glSecondaryColor
,glIndex
,glNormal
,glFogCoord
,glTexCoord
,glMultiTexCoord
,glVertexAttrib
,glEvalCoord
,glEvalPoint
,glArrayElement
,glMaterial
和glEdgeFlag
。 同样,可以使用glCallList
或glCallLists
执行仅包含前面命令的显示列表。 如果在glBegin
和glEnd
之间执行了其他任何GL命令,则会设置错误标志,并且该命令将被忽略。
因此,在Draw
函数中,您需要放置glBindTexture(GL_TEXTURE_2D, textureID);
和glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
在glBegin(GL_QUADS)
之前。 否则, glBindTexture
不会执行任何操作,因为它位于glBegin
,因此SecondBMP.bmp
仍绑定到目标GL_TEXTURE_2D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.