1

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

从模型类的子类声明纹理模型。

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

TextureModel子类的构造方法:

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();
}

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

模型和照明工作正常,但纹理没有出现。任何它不起作用的原因都会很好。

4

1 回答 1

2

为了添加评论,我在这里看到了一些东西:

  1. 正如评论中提到的,您需要先绑定纹理,然后才能将数据上传到它。使用 生成纹理后glGenTextures,您需要在尝试加载数据或使用设置参数之前将其设置为活动纹理glTexParameteri

  2. 您正在构建 mipmap,但不使用它们。要么设置GL_TEXTURE_MIN_FILTERGL_NEAREST_MIPMAP_LINEAR使用 mipmap,要么一开始就不构建它们。因为你只是在浪费纹理内存。

  3. glBegin在/之间绑定纹理是不合法的,glEnd就像你在drawTriangle. 将其绑定在glBegin.

  4. 请,开始glGetError在您的代码中使用。这将告诉您在您必须来要求找出错误之前您是否做错了事。(如果你一直在使用它,你会在这里发现 2/3 的错误)。

于 2012-04-24T19:00:47.343 回答