foo*_*512 6 opengl textures texture-mapping
我使用的是OpenGL 4.1和GLSL 410.我试图使用以下坐标对我制作的正方形进行纹理处理:
float points[] = {
-0.5, 0.5,
-0.5, -0.5,
0.5, -0.5,
-0.5, 0.5,
0.5, -0.5,
0.5, 0.5
};
Run Code Online (Sandbox Code Playgroud)
我像这样画广场:
glDrawArrays (GL_TRIANGLES, 0, 6);
Run Code Online (Sandbox Code Playgroud)
在我读过的所有教程中,作者使用元素缓冲区绘制正方形或只有四个顶点.这意味着我读过的所有教程都有与每个顶点对齐的纹理坐标.对我来说,我使用6个顶点,所以我不确定如何排列纹理坐标.
这样的坐标会适用于我的情况:
float texcoords[] = {
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0
};
Run Code Online (Sandbox Code Playgroud)
我已经做了很多阅读,但没有遇到任何像我一样使用六个顶点的人.
我的纹理坐标是否有效,如果没有,那么提出纹理坐标的最佳方法是什么.
是的,那会起作用的。您已将正方形分成 2 个三角形,并将纹理坐标映射到三角形的顶点。你的结果是什么?
看到这个问题。该代码使用一个数组作为顶点(尽管每个顶点都有 xyz 值),使用另一个数组作为纹理坐标。
定义顶点属性时需要小心。
例如,使用 2 个缓冲区设置顶点数据
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
glGenBuffers(1, &texbuffer);
glBindBuffer(GL_ARRAY_BUFFER, texbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(texcoords), texcoords, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0, // attribute 0
2, // 2 floats per vertex
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride -> tightly packed so make it zero
0); // array buffer offset
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, texbuffer);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glDrawArrays(GL_TRIANGLES, 0, 6);
Run Code Online (Sandbox Code Playgroud)
加载纹理(更新和设置采样器,请参阅评论)
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
GLuint TextureID = glGetUniformLocation(programID, "texture");
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
Run Code Online (Sandbox Code Playgroud)
顶点着色器
#version 410 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 texcoord;
out vec2 texture_coordinates;
uniform mat4 MVP;
void main() {
gl_Position = position;
texture_coordinates = texcoord;
}
Run Code Online (Sandbox Code Playgroud)
片段着色器
in vec2 texture_coordinates;
uniform sampler2D texture;
out vec4 colour;
void main() {
colour = texture2D(basic_texture, texture_coordinates);
}
Run Code Online (Sandbox Code Playgroud)