I have two textures. One is jpg and the other is png. I have rendered a cube and I want to use the jpg image as a background in every face of the cube and then have the png on this background. I tried mix()
but i can see the background through png and I don't want that. Is there any function that can do this for me?
Fragment Shader:
#version 330 core
struct Light {
vec3 direction;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
struct Material {
float shininess;
};
out vec4 FragColor;
in vec3 FragPos;
in vec3 Normal;
in vec2 TexCoords;
uniform vec3 viewPos;
uniform sampler2D texture1;
uniform sampler2D texture2;
uniform Light light;
uniform Material material;
void main() {
// ambient
vec3 ambient = light.ambient * mix(texture(texture1, TexCoords), texture(texture2, TexCoords), 0.0).rgb;
// diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(-light.direction);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = light.diffuse * diff * mix(texture(texture1, TexCoords), texture(texture2, TexCoords), 0.0).rgb;
// specular
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * spec * mix(texture(texture1, TexCoords), texture(texture2, TexCoords), 0.0).rgb;
vec3 result = ambient + diffuse + specular;
FragColor = vec4(result, 1.0);
}
texture1
is the png and texture2
is the jpg.
You need to mix the color depending on the alpha channel of the PNG texture. Assuming texture1 is the JPG and texture2 is the PNG, mix
texture1
and texture2
depending on texture2
's alpha channel:
vec4 color_jpg = texture(texture1, TexCoords);
vec4 color_png = texture(texture2, TexCoords);
vec3 color = mix(color_jpg.rgb, color_png.rgb, color_png.a);
Fragment shader:
void main()
{
vec4 color_jpg = texture(texture1, TexCoords);
vec4 color_png = texture(texture2, TexCoords);
vec3 color = mix(color_jpg.rgb, color_png.rgb, color_png.a);
// ambient
vec3 ambient = light.ambient * color;
// diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(-light.direction);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = light.diffuse * diff * color;
// specular
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * spec * color;
vec3 result = ambient + diffuse + specular;
FragColor = vec4(result, 1.0);
}