我第一次尝试使用OpenGL ES 2.0在平原上渲染纹理。我一定是做错了,因为它总是黑的。
纹理来自资源中的图像。
这是我的渲染引擎的代码:
初始化:
...//program creation and linking
UIImage* image = [UIImage imageNamed:@"marilyn.jpg"];
GLubyte* textureData = (GLubyte *)malloc(image.size.width * image.size.height * 4);
CGContext* textureContext = CGBitmapContextCreate(textureData, image.size.width, image.size.height, 8, image.size.width * 4, CGImageGetColorSpace(image.CGImage), kCGImageAlphaPremultipliedLast);
CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (CGFloat)image.size.width, (CGFloat)image.size.height), image.CGImage);
CGContextRelease(textureContext);
glGenTextures(1, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.size.width, image.size.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);
...//frame and render buffers...
呈现
glViewport(0, 0, backingWidth, backingHeight);
glClearColor(0.3f, 0.3f, 0.4f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
glUniformMatrix4fv(u_modelView, 1, GL_FALSE, modelView.Pointer());
glUniformMatrix4fv(u_projection, 1, GL_FALSE, proj.Pointer());
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(u_sampler, 0);
const GLfloat squareVertices[] = {
-200.0f, -200.0f,
200.0f,-200.0f,
-200.0f, 200.0f,
200.0f,200.0f,
};
const GLfloat squareTextureCoords[] = {
1.0, 1.0,
1.0, 0.0,
0.0, 1.0,
0.0, 0.0,
};
glVertexAttribPointer(p_texture.a_position, 2, GL_FLOAT, GL_FALSE, 0, squareVertices);
glEnableVertexAttribArray(p_texture.a_position);
glVertexAttribPointer(p_texture.a_textureCoord, 2, GL_FLOAT, GL_FALSE, 0, squareTextureCoords);
glEnableVertexAttribArray(p_texture.a_textureCoord);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
我很遗憾放下所有代码,但我一直在寻找几个小时,我找不到有什么问题。
我所看到的只是一个黑色方块,而不是玛丽莲的照片。
编辑:我忘了展示着色器 顶点着色器:attribute vec4 position;
attribute vec2 texture_coord;
varying vec2 textureCoord;
uniform mat4 Projection;
uniform mat4 ModelView;
void main(void)
{
gl_Position = Projection * ModelView * position;
textureCoord = texture_coord;
}
Fragment Shader:
varying mediump vec2 textureCoord;
uniform sampler2D tex;
void main(void)
{
gl_FragColor = texture2D(tex, textureCoord);
}
答案 0 :(得分:2)
对不起,正如我在对cplusogl回答的评论中所说,问题是我没有使用方形纹理,边的大小是2的幂。
答案 1 :(得分:1)
你是如何设置纹理的?某些设备仅支持GL_CLAMP_TO_EDGE属性。在OGL es 2.0中,等效代码如下所示:
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S,
GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T,
GLES20.GL_CLAMP_TO_EDGE);
答案 2 :(得分:1)
OGL / ES 2可以挑选纹理大小。建议您查看: