纹理不会出现 - GLUT OpenGL

Texture Won't Appear - GLUT OpenGL

本文关键字:GLUT OpenGL 纹理      更新时间:2023-10-16

我在尝试使用类在 OpenGL GLUT 项目中加载纹理时遇到问题。下面是一些包含纹理内容的代码:

从模型类

的子类声明纹理模型。

TextureModel * title = new TextureModel("Box.obj", "title.raw");

纹理模型子类的构造函数方法:

TextureModel(string fName, string tName) : Model(fName), textureFile(tName)
{   
    material newMat = {{0.63,0.52,0.1,1.0},{0.63,0.52,0.1,1.0},{0.2,0.2,0.05,0.5},10};
    Material = newMat;
    // enable texturing
    glEnable(GL_TEXTURE_2D);
    loadcolTexture(textureFile);
    glGenTextures(1, &textureRef);
    // specify the filtering method
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    // associate the image read in to the texture to be applied
    gluBuild2DMipmaps(GL_TEXTURE_2D, 3, 256, 256, GL_RGB, GL_UNSIGNED_BYTE, image_array);
}

纹理加载功能,用于读取RAW文件中的数据:

int loadcolTexture(const string fileName) {
ifstream inFile;
inFile.open(fileName.c_str(), ios::binary );
if (!inFile.good())
{
    cerr  << "Can't open texture file " << fileName << endl;
    return 1;
}
inFile.seekg (0, ios::end);
int size = inFile.tellg();
image_array = new char [size];
inFile.seekg (0, ios::beg);
inFile.read (image_array, size);
inFile.close();
return 0;}

绘制三角形的方法:

virtual void drawTriangle(int f1, int f2, int f3, int t1, int t2, int t3, int n1, int n2, int n3)
{
    glColor3f(1.0,1.0,1.0);
    glBegin(GL_TRIANGLES);
    glBindTexture(GL_TEXTURE_2D, textureRef);
    glNormal3fv(&normals[n1].x);
    glTexCoord2f(textures[t1].u, textures[t1].v);
    glVertex3fv(&Model::vertices[f1].x);
    glNormal3fv(&normals[n2].x);
    glTexCoord2f(textures[t2].u, textures[t2].v);
    glVertex3fv(&Model::vertices[f2].x);
    glNormal3fv(&normals[n3].x);
    glTexCoord2f(textures[t3].u, textures[t3].v);
    glVertex3fv(&Model::vertices[f3].x);
    glEnd();
}

我还启用了照明、深度测试和双缓冲。

模型和光照工作正常,但纹理不显示。它不起作用的任何原因都会很棒。

为了补充评论,我在这里看到了一些事情:

  1. 如注释中所述,您需要先绑定纹理,然后才能将数据上传到其中。使用 glGenTextures 生成纹理后,您需要将其设置为活动纹理,然后再尝试加载数据或使用 glTexParameteri 设置参数

  2. 您正在构建mipmap,但没有使用它们。要么将GL_TEXTURE_MIN_FILTER设置为GL_NEAREST_MIPMAP_LINEAR以利用 mipmap,要么首先不构建它们。就像你只是在浪费纹理内存一样。

  3. drawTriangle中那样在glBegin/glEnd之间绑定纹理是不合法的。在glBegin之前绑定它。

  4. 拜托,
  5. 拜托开始在你的代码中使用glGetError。这会告诉你你是否做错了事情,然后你不得不来要求找到你的错误。(如果你一直在使用它,你会在这里发现 2/3 的错误)。