在OpenGL中使用纹理渲染对象

时间:2014-05-16 20:53:20

标签: c++ opengl

我正在尝试在我的模型中放置纹理,但它不起作用,模型是在没有纹理的情况下绘制的。

这个函数加载纹理,起初它应该工作得很好,因为我已经在另一个程序中使用它了。我在main函数中调用此函数,将结果放在名为modelTexture的全局变量中。

GLuint initTexture(char* filename) {
   BITMAPINFO *info;
   GLubyte *ptr, *bits, *rgba, *rgbaptr;
   GLuint texture, temp;
   GLenum type;
   bits = LoadDIBitmap(filename, &info);
   if (bits == (GLubyte *)0) {
   return NULL;
   }
   if (info->bmiHeader.biHeight == 1)
       type = GL_TEXTURE_1D;
   else
   type = GL_TEXTURE_2D;
   glGenTextures(1, &texture);
   glBindTexture(type, texture);
   glTexParameteri(type, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
   glTexParameteri(type, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
   glTexParameteri(type, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameteri(type, GL_TEXTURE_WRAP_T, GL_REPEAT);
   rgba = (GLubyte *)malloc(info->bmiHeader.biWidth * info->bmiHeader.biHeight * 4);
   int i = info->bmiHeader.biWidth * info->bmiHeader.biHeight;
   for(rgbaptr = rgba, ptr = bits;  i > 0; i--, rgbaptr += 4, ptr += 3){
       rgbaptr[0] = ptr[2];
       rgbaptr[1] = ptr[1];
       rgbaptr[2] = ptr[0];
       rgbaptr[3] = (ptr[0] + ptr[1] + ptr[2])/3;
   }
   gluBuild2DMipmaps(GL_TEXTURE_2D, 4, info->bmiHeader.biWidth, info->bmiHeader.biHeight, GL_RGBA, GL_UNSIGNED_BYTE, rgba);
   return texture;
}

所以,这是显示回调,我绘制模型。

void renderGL(void){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glFrontFace(GL_CW);
    glCullFace (GL_BACK);
    glEnable(GL_CULL_FACE);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(angle, aspRatio, zNear, zFar);
    glMatrixMode(GL_MODELVIEW);
updateCamera();
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, modelTexture);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    int i;
    for (i = 0; i < object.NumTris; i++){
        glBegin(GL_TRIANGLES);
            glNormal3f(object.Tris[i].normal[0].x, object.Tris[i].normal[0].y, object.Tris[i].normal[0].z);
            glTexCoord2f(0.0f, 0.0f);
            glVertex3f(object.Tris[i].v0.x, object.Tris[i].v0.y, object.Tris[i].v0.z);
            glNormal3f(object.Tris[i].normal[1].x, object.Tris[i].normal[1].y, object.Tris[i].normal[1].z);
            glTexCoord2f(0.5f, 1.0f);
            glVertex3f(object.Tris[i].v1.x, object.Tris[i].v1.y, object.Tris[i].v1.z);
            glNormal3f(object.Tris[i].normal[2].x, object.Tris[i].normal[2].y, object.Tris[i].normal[2].z);
            glTexCoord2f(1.0f, 0.0f);
            glVertex3f(object.Tris[i].v2.x, object.Tris[i].v2.y, object.Tris[i].v2.z);
        glEnd();
    }
    glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
}

那么,有什么我做错了或忘了做什么?

0 个答案:

没有答案