我正在尝试在 OpenGL 中渲染棋盘格,但我得到了不正确的输出。[棋盘] http://s9.postimg.org/g3wk1py4f/large_checkerboard.png “大棋盘”
我试图缩小问题的范围,我注意到当我尝试绘制一个 11 x 11 的网格时,我在垂直方向上只得到 10 个像素 [小棋盘] http://s12.postimg.org/olu7575jd/small_checkerboard.png “小棋盘”
质地本身还可以。我怀疑问题出在顶点坐标上。这是代码:
纹理创建:
const int size = 11;
unsigned char buffer[size * size * 4];
for (size_t i = 0; i < size; i++)
{
for (size_t j = 0; j < size; j++)
{
unsigned char rgb = i % 2 == 1 || j % 2 == 1 ? 255 : 0;
int index = (i * size + j) * 4;
buffer[index] = rgb;
buffer[index + 1] = rgb;
buffer[index + 2] = rgb;
buffer[index + 3] = 255;
}
}
纹理参数:
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
顶点:(屏幕尺寸为 1024 * 768,我在右上四分之一处绘制没有任何变换)
float w = size / 512.0f;
float h = size / 384.0f;
GLfloat vertices[] =
{
0.0f, h, 0.0f, 1.0f,
0.0f, 0.0f, 0.0f, 0.0f,
w, h, 1.0f, 1.0f,
w, 0.0f, 1.0f, 0.0f
};
int positionLocation = glGetAttribLocation(program.getId(), "a_position");
int textureLocation = glGetAttribLocation(program.getId(), "a_texCoord");
glEnableVertexAttribArray(positionLocation);
glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), vertices);
glEnableVertexAttribArray(textureLocation);
glVertexAttribPointer(textureLocation, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), vertices + 2);
glUniform1i(textureLocation, 0);
绘画:
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
和着色器:
const char* VertexShaderCode =
"attribute vec4 a_position; \n"
"attribute vec2 a_texCoord; \n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_texCoord = a_texCoord; \n"
"}";
const char* FragmentShaderCode =
"uniform sampler2D s_texture; \n"
"varying vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_FragColor = texture2D(s_texture, v_texCoord); \n"
"}";