纹理坐标范围是0~1 ,如果设置的值超过1 怎么办?那么就由GL_TEXTURE_WRAP_S、GL_TEXTURE_WRAP_T参数决定怎么做。
使用函数glTexParameteri() 设置纹理参数。
代码如下:
设置纹理参数
static unsigned createTexture(int w, int h, const void* data) {
unsigned texId;
glGenTextures(1, &texId);
glBindTexture(GL_TEXTURE_2D, texId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//设置纹理参数 GL_TEXTURE_WRAP_S 为 GL_REPEAT 表示纹理X方向循环使用纹理
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//设置纹理参数 GL_TEXTURE_WRAP_T 为 GL_MIRRORED_REPEAT 表示纹理Y方向镜像循环使用纹理
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
return texId;
}
绘制
static void render(GLFWwindow * window) {
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//指定数据 顶点坐标 对应 纹理坐标
Vertex cubeVertices[] =
{
{ -1.0f, -1.0f, 1.0f, 0, 0 },
{ 1.0f, -1.0f, 1.0f, 3, 0 },
{ 1.0f, 1.0f, 1.0f, 3, 2 },
{ -1.0f, 1.0f, 1.0f, 0, 2 },
{ -1.0f, -1.0f, -1.0f, 0, 0 },
{ -1.0f, 1.0f, -1.0f, 1, 0 },
{ 1.0f, 1.0f, -1.0f, 1, 1 },
{ 1.0f, -1.0f, -1.0f, 0, 1 },
{ -1.0f, 1.0f, -1.0f, 0, 0 },
{ -1.0f, 1.0f, 1.0f, 1, 0 },
{ 1.0f, 1.0f, 1.0f, 1, 1 },
{ 1.0f, 1.0f, -1.0f, 0, 1 },
{ -1.0f, -1.0f, -1.0f, 0, 0 },
{ 1.0f, -1.0f, -1.0f, 1, 0 },
{ 1.0f, -1.0f, 1.0f, 1, 1 },
{ -1.0f, -1.0f, 1.0f, 0, 1 },
{ 1.0f, -1.0f, -1.0f, 0, 0 },
{ 1.0f, 1.0f, -1.0f, 1, 0 },
{ 1.0f, 1.0f, 1.0f, 1, 1 },
{ 1.0f, -1.0f, 1.0f, 0, 1 },
{ -1.0f, -1.0f, -1.0f, 0, 0 },
{ -1.0f, -1.0f, 1.0f, 1, 0 },
{ -1.0f, 1.0f, 1.0f, 1, 1 },
{ -1.0f, 1.0f, -1.0f, 0, 1 },
};
glMatrixMode(GL_MODELVIEW);
#if 0
glEnable(GL_DEPTH_TEST);
glInterleavedArrays( GL_T2F_V3F, sizeof(Vertex), cubeVertices );
#else
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
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);
#endif
// 清成单位矩阵
glLoadIdentity();
// 产生一个矩阵
glTranslatef(0, 0, -4);
for(int i = 0; i < 6; ++i) {
glBindTexture(GL_TEXTURE_2D, _texture[i%2]);
glDrawArrays(GL_QUADS, i * 4, 4);
}
glfwSwapBuffers(window);
glfwPollEvents();
}