0

I am new in OpenGL ES and I am trying to do some basic stuff as part of my learning curve. I was able to render two meshes, a sphere and a cube with two glDrawArrays calls. I am trying to load a different texture to wrap around the cube and sphere but what is happening is that the last loaded texture is wrapped to both meshes. Does anyone know why this might be happening?

Here is the code for the mesh:

glEnable(GL_DEPTH_TEST);

glGenVertexArraysOES(1, &vertexArray);
glBindVertexArrayOES(vertexArray);

glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeMeshVerts, meshVerts, GL_STATIC_DRAW);

glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 4*8, BUFFER_OFFSET(0));

glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 4*8, BUFFER_OFFSET(4*3));

glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 4*8, BUFFER_OFFSET(4*6));

// Texture
// Create image from file
NSString *path = [[NSBundle mainBundle] pathForResource:textureImage ofType:@"jpg"];
NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
UIImage *image = [[UIImage alloc] initWithData:texData];

// Generates a new OpenGL ES texture buffer and // initializes the buffer contents using pixel data from the // specified Core Graphics image, cgImage.

[TextureLoader textureWithCGImage:image.CGImage options:nil error:NULL];

glBindVertexArrayOES(0);

Here is the draw code:

glBindVertexArrayOES(_vertexArray);

// Render the object with ES2
glUseProgram(_program);

// Set the sampler texture unit to 0
glUniform1i (uniforms[UNIFORM_TEXTURE_MATRIX], 0);

glDrawArrays(GL_TRIANGLES, 0, numVertices);
4

1 回答 1

1

在渲染之前,您没有将纹理绑定到采样器。首先,您需要保留对由GLKTextureInfo返回的对象的引用textureWithCGImage:,然后您可以使用glBindTexture纹理名称将其绑定到当前的采样器。例如

GLKTextureInfo *tex = [TextureLoader textureWithCGImage:image.CGImage options:nil error:NULL];
...
glBindTexture(GL_TEXTURE_2D, tex.name);

您需要在每次绘制调用之前执行此操作,以便为采样器设置正确的纹理。您可以将所需的每个纹理绑定到不同的采样器,然后也只需传入正确的采样器制服。

于 2012-12-15T14:57:10.720 回答