I am writing an openGL program and have multiple models drawn into the environment, but I don't know how to apply different textures to each of those models, so for now they all have the same texture. I've read that I need to add multiple texture units into the program or use a texture atlas. A texture atlas seems more complicated, so I'm trying to add texture units.
The way I thought this process worked is:
- Generate two texture units with glGenTextures.
- Bind the data of the first image to the first texture unit with glBindTexture and glTexImage2D.
- Do the same with the second image.
From here, I thought I could tell openGL which texture unit I want to use using glActiveTexture. This seems to work with just one texture (i.e. skip step 3) but fails with two or more.
I'm sure I'm missing something, so could someone point me in the right direction?
//Generate textures
int texturec=2;
int w[texturec],h[texturec];
unsigned char *data[texturec];
data[0]=getImage(&w[0],&h[0],"resources/a.png");
data[1]=getImage(&w[1],&h[1],"resources/b.png");
//Apply textures
GLuint textures[texturec];
glGenTextures(texturec, textures);
//Bind a.png to the first texture unit
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, w[0], h[0], 0, GL_RGB, GL_UNSIGNED_BYTE, data[0]);
//Bind b.png to the second texture unit
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, w[1], h[1], 0, GL_RGB, GL_UNSIGNED_BYTE, data[1]);
glActiveTexture(GL_TEXTURE0);
//Not super clear on what this does, but it needs to be here.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
And here are my shaders:
Fragment:
#version 330 core
in vec2 UV;
out vec3 color;
uniform sampler2D textureSampler;
void main(){
color=texture(textureSampler,UV).rgb;
}
Vertex:
#version 330 core
layout(location=0) in vec3 vertexPos;
layout(location=1) in vec2 vertexUV;
out vec2 UV;
uniform mat4 MVP;
void main(){
gl_Position=MVP*vec4(vertexPos,1);
UV=vertexUV;
}
Edit:
Here is my new code after applying Rabid76's suggestions:
//Generate textures
int texturec=2;
int w[texturec],h[texturec];
unsigned char *data[texturec];
data[0]=getImage(&w[0],&h[0],"resources/a.png");
data[1]=getImage(&w[1],&h[1],"resources/b.png");
//Apply textures
GLuint textures[texturec];
glGenTextures(texturec, textures);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, w[0], h[0], 0, GL_RGB, GL_UNSIGNED_BYTE, data[0]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, w[1], h[1], 0, GL_RGB, GL_UNSIGNED_BYTE, data[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//Shaders
programID=loadShaders("shaders/vertex.shader","shaders/fragment.shader");
glUseProgram(programID);
//Use texture unit 1
glActiveTexture(GL_TEXTURE1);
GLint texLoc=glGetUniformLocation(programID, "textureSampler");
glUniform1i(texLoc, 1);