C++ 纹理赢得';t-GLUT OpenGL

C++ 纹理赢得';t-GLUT OpenGL,c++,opengl,textures,glut,texture-mapping,C++,Opengl,Textures,Glut,Texture Mapping,我在使用类在OpenGL GLUT项目中加载纹理时遇到问题。 下面是一些包含纹理的代码: 从模型类的子类声明纹理模型 TextureModel*title=新的TextureModel(“Box.obj”、“title.raw”) TextureModel子类的构造函数方法: TextureModel(string fName, string tName) : Model(fName), textureFile(tName) { material newMat = {{0.63,0

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

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

TextureModel*title=新的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);
}
用于读取原始文件中数据的纹理加载函数:

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;}
我还启用了照明、深度测试和双缓冲


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

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

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

  • 您正在构建mipmap,但没有使用它们。将
    GL\u纹理\u MIN\u过滤器设置为
    GL\u最近的\u MIPMAP\u线性
    以利用MIPMAP,或者不首先构建它们。你只是在浪费纹理内存

  • glBegin
    /
    glEnd
    之间绑定纹理是不合法的,就像您在
    drawTriangle
    中所做的那样。在
    glBegin
    之前绑定它

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


  • 您至少错过了对
    TextureModel
    构造函数中的
    glBindTexture
    的调用。
    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();
    }