车子有光滑的部分,也有轮胎粗糙的部分,所以我们需要通过引入漫反射和镜面反射贴图来扩展系统。 这些使我们能够更精确地影响物体的漫反射(并间接影响环境分量,因为它们无论如何都应该相同)和镜面反射分量。
基础知识:
Diffuse maps(漫反射贴图)
使用一张贴图,作为漫反射的作用画面。
Specular maps(镜面反射贴图)
我们可以仅将纹理贴图用于镜面高光。我们需要生成一个黑色和白色(或者你喜欢的颜色)纹理来定义对象每个部分的镜面反射强度。 高光贴图的示例如下图所示:
代码解析:
#version 330 core
out vec4 FragColor;
//定义材质结构体
struct Material {
sampler2D diffuse;
sampler2D specular;
float shininess;
};
//定义光线结构体
struct Light {
vec3 position;
vec3 ambient;
vec3 diffuse;
vec3 specular;
};
//片面位置,法线,以及贴图坐标,在定义vertices中有定义
// positions normals exture coords
// -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
in vec3 FragPos;
in vec3 Normal;
in vec2 TexCoords;
uniform vec3 viewPos;
uniform Material material;
uniform Light light;
void main()
{
// ambient
vec3 ambient = light.ambient * texture(material.diffuse, TexCoords).rgb;
// diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(light.position - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = light.diffuse * diff * texture(material.diffuse, TexCoords).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 * texture(material.specular, TexCoords).rgb;
vec3 result = ambient + diffuse + specular;
FragColor = vec4(result, 1.0);
}
其中texture(xxxxxx)是在生成图片信息,material.diffuse 属于simpler2D diffuse,这个在CPP中使用 :
// load textures (we now use a utility function to keep the code more organized)
// -----------------------------------------------------------------------------
unsigned int diffuseMap = loadTexture(FileSystem::getPath("resources/textures/container2.png").c_str());
unsigned int specularMap = loadTexture(FileSystem::getPath("resources/textures/container2_specular.png").c_str());
// shader configuration 设定diffuse为texture0,specular为texture1
// --------------------
lightingShader.use();
lightingShader.setInt("material.diffuse", 0);
lightingShader.setInt("material.specular", 1);
while(true)中:
// bind diffuse map 把diffuseMap绑定进texture0中
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffuseMap);
// bind specular map
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, specularMap);