#include"utils.h"
unsigned char * DecodeBMP(unsigned char bmpFileData,int&width,int&height)
{
if(0x4D42==(unsigned short*)bmpFileData)
{
int pixeiDataOffset=*((int*)(bmpFileData+10));
width=*((int*)(bmpFileData+18));
height=*((int*)(bmpFileData+22));
unsigned char*pixelData=bmpFileData+pixeiDataOffset;//像素块的起始位置
for(int i=0;i<width*height*3;i+=3)
{
unsigned char temp=pixelData[i];
pixelData[i]=pixelData[i+2];
pixelData[i+2]=temp;
}
return pixelData;
}
return nullptr;
}
GLuint CreateTexture2D(unsigned char *pixelData,int width,int height,GLenum type)
{
GLuint texture;
glGenTextures(1,&texture);//第一个表示申请一个纹理对象
glBindTexture(GL_TEXTURE_2D,texture);//对当前纹理对象进行指定
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, type, width, height, 0,
type, GL_UNSIGNED_BYTE, pixelData); //最后一个参数是 你的纹理在哪 此时纹理对象就已经生成了
glBindTexture(GL_TEXTURE_2D,0);//最后将当前纹理设置成为0号纹理以免后面的操作对texture纹理造成影响 不想再被修改
return texture;
}
GLuint CreateTexture2DFromBMP(const char *bmpPath)
{
int nFileSize=0;
unsigned char *bmpFileContent=LoadFileContent(bmpPath,nFileSize);
if(bmpFileContent==nullptr)
{
return 0;
}
int bmpWidth=0,bmpHeight=0;
unsigned char *pixelData=DecodeBMP(bmpFileContent,bmpWidth,bmpHeight);
if(bmpWidth==0)
{
delete bmpFileContent;
return 0;
}
GLuint texture=CreateTexture2D(pixelData,bmpWidth,bmpHeight,GL_RGB);
delete bmpFileContent;
return texture;
}
#include"scene.h"
#include"utils.h"
GLuint texture;
void Init()
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
int nFileSize =0;
unsigned char *bmpFileContent=LoadFileContent("Res/test.bmp",nFileSize);
int bmpWidth=0,bmpHeight=0;
unsigned char *pixelData=DecodeBMP(bmpFileContent,bmpWidth,bmpHeight);
texture=CreateTexture2D(pixelData,bmpWidth,bmpHeight,GL_RGB);
}
void Draw()
{
glClearColor(1.0f,0.0f,0.0f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,texture);
glBegin(GL_QUADS);
glColor3f(1.0,1.0,1.0);
glTexCoord2f(0.0f,0.0f);
glVertex3f(-0.1f,-0.1f,-0.4f);
glTexCoord2f(1.0f,0.0f);
glVertex3f(0.1f,-0.1f,-0.4f);
glTexCoord2f(1.0f,1.0f);
glVertex3f(0.1f,0.1f,-0.4f);
glTexCoord2f(0.0f,1.0f);
glVertex3f(-0.1f,0.1f,-0.4f);
glEnd();
}