我有两种纹理。一个是jpg,一个是PNG。我已经渲染了一个立方体,我想使用jpg图像作为背景在立方体的每一个面,然后在这个背景上有png。我尝试了mix()
,但我可以通过png看到背景,我不希望这样。有没有什么功能可以为我做到这一点?
片段着色器:
#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
是png,texture2
是JPG。
您需要根据PNG纹理的alpha通道混合颜色。假设texture1是JPG而texture2是PNG,混合
texture1
和texture2
取决于texture2
的alpha通道:
vec4 color_jpg = texture(texture1, TexCoords);
vec4 color_png = texture(texture2, TexCoords);
vec3 color = mix(color_jpg.rgb, color_png.rgb, color_png.a);
片段着色器:
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);
}