PDA

View Full Version : Multiple texture mapping



yuval.sightec
06-13-2016, 03:12 AM
I tried to search online but I couldn't understand how to add a texture for my model. (It can be seted from the start)
I having trouble with it and I would like for some help in the changes I should make with my code.

My texture setting function is:


void Texture::setTexture(unsigned char* data, unsigned int width, unsigned int height) {
glGenTextures(1, &m_texture[unit]); // Genatate 1 texture in m_texture
glBindTexture(GL_TEXTURE_2D, m_texture[unit]);


glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);


glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);


My bind function:

void Texture::Bind(unsigned int unit) {
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, m_texture[unit]);


And My shaders looks like this:

attribute vec3 position; // Position values
attribute vec2 texCoord; // Texture coordinates values
attribute vec3 normal; // Normal

varying vec2 texCoord0;
varying vec3 normal0;

uniform mat4 transform;

void main()
{
gl_Position = transform * vec4(position, 1.0);
texCoord0 = texCoord;
normal0= (transform * vec4(normal, 0.0)).xyz;
}
fragment shader:

varying vec2 texCoord0;
varying vec3 normal0;

uniform sampler2D diffuse;

void main()
{
gl_FragColor = texture2D(diffuse, texCoord0) *
clamp(dot(-vec3(0,0,1), normal0), 1.0, 1.0);
}


How can I add another texture? And what changes should I make in my Mesh class.
Sorry for the stupid question, I'm new in openGL :)
Thanks in advance!

john_connor
06-13-2016, 10:48 AM
consider a fragmentshader like that one:


in vec2 texcoords;

uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;

uniform int usetexture = 0;


void main
{
vec4 color;

if (usetexture == 0)
color = texture(tex0, texcoords);
if (usetexture == 1)
color = texture(tex1, texcoords);
if (usetexture == 2)
color = texture(tex2, texcoords);

gl_FragColor = color;
}



here you can controll via the uniform var "usetexture" which texture to use

before the drawcall you have to upload separate uniforms to those samplers:


int location;

location = glGetUniformLocation(program, "tex0");
glUniform1i(location, 0);

location = glGetUniformLocation(program, "tex1");
glUniform1i(location, 1);

location = glGetUniformLocation(program, "tex2");
glUniform1i(location, 2);

// then bind the textures to those samplers
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, m_texture[0]);

glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, m_texture[1]);

glActiveTexture(GL_TEXTURE0 + 2);
glBindTexture(GL_TEXTURE_2D, m_texture[2]);

glDrawArrays(...);