简体   繁体   中英

How to load different textures for each mesh in OpenGL ES 2.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);

You are not binding the textures to the sampler before rendering. First you need to keep a reference to the GLKTextureInfo object returned by textureWithCGImage: , then you can use glBindTexture with the texture name to bind it to the current samper. eg

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

You will need to do this before each draw call to set the correct texture to the sampler. You can bind each texture you need to different samplers and then just pass in the correct sampler uniform also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM