纹理映射
1.扩展顶点结构体 增加uv坐标
struct Vertex
{
float x, y, z;
float u,v;
};
声明纹理句柄标识
GLuint _texture;
初始化对纹理相关进行设置
开启纹理映射
生成纹理缓存
绑定句柄标识到当前操作纹理对象
随机生成颜色作为纹理数据
纹理滤波设置
根据上面的data生成一个2D纹理
绘制时候 开启纹理数组
指定uv坐标
#include <windows.h>
#include <tchar.h>
#include <math.h>
#include "CELLMath.hpp"
#include "OpenGLWindow.h"
#include <vector>
using namespace CELL;
struct Vertex
{
float x, y, z;
float u,v;
};
class SamplerTexture :public OpenGLWindow
{
GLuint _texture;
public:
SamplerTexture()
{
}
virtual void onInitGL()
{
glEnable(GL_TEXTURE_2D);
glGenTextures(1,&_texture);
glBindTexture(GL_TEXTURE_2D,_texture);
char* data = new char[128*128*4];
for(int i=0;i<128*128*4;i++)
{
data[i]=rand()%255;
}
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,128,128,0,GL_RGBA,GL_UNSIGNED_BYTE,data);
}
virtual void render()
{
#define M_PI (3.14159265358979323846)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60,double(800/600),0.1,1000);
Vertex cubeVertices[] =
{
{
-1.0f,-1.0f, 1.0f, 0, 0 },
{
1.0f,-1.0f, 1.0f, 0, 1 },
{
1.0f, 1.0f, 1.0f, 1, 1 },
{
-1.0f, 1.0f, 1.0f, 1, 0 },
};
glMatrixMode(GL_MODELVIEW); //模型矩阵操作
glBindTexture(GL_TEXTURE_2D,_texture);
glEnable(GL_DEPTH_TEST);
//glInterleavedArrays(GL_C4UB_V3F,0,cubeVertices);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3,GL_FLOAT,sizeof(Vertex),&cubeVertices[0].x);
glTexCoordPointer(2,GL_FLOAT,sizeof(Vertex),&cubeVertices[0].u);
glLoadIdentity();
glTranslatef(0,0,-5);
//glRotatef(_angle,1,0,0);
//glScalef(1,2,2);
glDrawArrays(GL_QUADS,0, 4);
}
};
int __stdcall WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd
)
{
SamplerTexture instance;
instance.main(800,600);
return 0;
}
使用FreeImage库读取图片生成纹理
1.引入头文件,工程配置对应的lib库文件,引入dll
2.增加生成纹理的方法
unsigned createTextureFromImage(const char* fileName)
{
FREE_IMAGE_FORMAT fifmt = FreeImage_GetFileType(fileName, 0);
if (fifmt == FIF_UNKNOWN)
{
return 0;
}
FIBITMAP *dib = FreeImage_Load(fifmt, fileName,0);
FREE_IMAGE_COLOR_TYPE type = FreeImage_GetColorType(dib);
FIBITMAP* temp = dib;
dib = FreeImage_ConvertTo32Bits(dib);
FreeImage_Unload(temp);
BYTE* pixels = (BYTE*)FreeImage_GetBits(dib);
int width = FreeImage_GetWidth(dib);
int height = FreeImage_GetHeight(dib);
for (int i = 0 ;i < width * height * 4 ; i+=4 )
{
BYTE temp = pixels[i];
pixels[i] = pixels[i + 2];
pixels[i + 2] = temp;
}
unsigned res = createTexture(width,height,pixels);
FreeImage_Unload(dib);
return res;
}
unsigned createTexture(int w,int h,const void* data)
{
unsigned texId;
glGenTextures(1,&texId