【发布时间】:2018-01-13 02:38:39
【问题描述】:
我正在尝试在 Android 中使用 C++ 渲染一个带有纹理的简单正方形,但在使用纹理时遇到了一些问题。
这是准备 OpenGL ES 的代码
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
// positions // colors // texture coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
unsigned int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// texture coord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
这里是顶点着色器:
attribute vec4 vertexPosition;
attribute vec2 vertexTexCoord;
varying vec2 texCoord;
void main()
{
gl_Position = vec4(vertexPosition.x, vertexPosition.y, vertexPosition.z, 1.0);
texCoord = vertexTexCoord;
}
片段着色器:
precision mediump float;
uniform sampler2D texSampler2D;
varying vec2 texCoord;
void main()
{
gl_FragColor = texture2D(texSampler2D, texCoord);
}
但是当我在 Android 上运行这段代码时,纹理没有正确放置。
原来的纹理是这样的:
我做错了什么?
【问题讨论】:
-
两件事是显而易见的。它不是一个正方形,而且 uv 坐标看起来很乱。您确定顶点声明不会将颜色值与纹理坐标混淆吗?否则显示带有 uv 贴图颜色的四边形可能会有所帮助。
-
如果你的顶点布局是vec3、vec3、vec2,为什么在顶点着色器中你有vec4、vec2和vec2?
-
你确定纹理坐标是属性2吗?