www.pudn.com > vessel2.rar > TEXTURE.CPP
// Texture.cpp: implementation of the Texture class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MySDOpenGL.h" #include "Texture.h" #include#include "MySDOpenGLDoc.h" #include "MySDOpenGLView.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif extern GLuint texture[3]; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Texture::Texture() { } Texture::~Texture() { } // 装入一个BMP位图 AUX_RGBImageRec *Texture::LoadBMP(const char *Filename) { FILE *File=NULL; // 文件指针 if (!Filename) { return NULL; // 如果文件指针不存在,则返回 } File=fopen(Filename,"r");// 核实文件是否存在 if (File) // 如果文件存在 { fclose(File); // 关闭文件 return auxDIBImageLoad(Filename);// 读入位图数据,并返回 } return NULL; // 如果读入失败,则返回NULL } // 装入BMP位图,并转换为纹理 GLuint Texture::LoadGLTexture( const char *filename ) { AUX_RGBImageRec *pImage; // 常见保存纹理的空间 GLuint Texture = 0; // 纹理的ID pImage = LoadBMP( filename ); // 读入指定文件的位图数据 if ( pImage != NULL && pImage->data != NULL ) // 如果纹理图像存在 { glGenTextures(1, &Texture); // 典型的纹理生成方法 glBindTexture(GL_TEXTURE_2D, Texture); glTexImage2D(GL_TEXTURE_2D, 0, 3, pImage->sizeX, pImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, pImage->data); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); free(pImage->data); // 释放纹理图像内存 free(pImage); // 释放图像结构 } return Texture; // 返回纹理 } // 装入位图并将位图转换为纹理 int Texture::LoadTextures() { int Status=FALSE; // 状态指示器 AUX_RGBImageRec *TextureImage[1]; // 创建保存纹理的空间 memset(TextureImage,0,sizeof(void *)*1); if (TextureImage[0]=LoadBMP("Data/Floor.bmp")) { Status=TRUE; glGenTextures(1, &texture[1]); // 创建第1号纹理 glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); } if (TextureImage[0]=LoadBMP("Data/FloorB.bmp")) { Status=TRUE; glGenTextures(1, &texture[2]); // 创建第2号纹理 glBindTexture(GL_TEXTURE_2D, texture[2]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data); } if (TextureImage[0]) // 如果纹理存在 { if (TextureImage[0]->data) // 如果纹理数据存在 { free(TextureImage[0]->data); // 释放纹理数据内存 } free(TextureImage[0]); // 释放图像结构 } return Status; // 返回状态 }