[英]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.